Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(snaptrade): pick one security when a ticker has duplicate rows (#3999)

jaysbeekaybe69c4ea103e
diff --git a/app/models/snaptrade_account/activities_processor.rb b/app/models/snaptrade_account/activities_processor.rb
index b78b12bd2e..552e0466a9 100644
--- a/app/models/snaptrade_account/activities_processor.rb
+++ b/app/models/snaptrade_account/activities_processor.rb
@@ -220,7 +220,7 @@ class SnaptradeAccount::ActivitiesProcessor
end
# Resolve security
- security = resolve_security(ticker, symbol_data)
+ security = resolve_security(ticker, symbol_data, account: account, account_provider_id: @snaptrade_account.account_provider&.id)
unless security
capture_skipped_trade("unresolved_security", "security could not be resolved",
external_id: external_id, activity_type: activity_type, ticker: ticker)
diff --git a/app/models/snaptrade_account/data_helpers.rb b/app/models/snaptrade_account/data_helpers.rb
index dd1fa7b939..981dc7cba0 100644
--- a/app/models/snaptrade_account/data_helpers.rb
+++ b/app/models/snaptrade_account/data_helpers.rb
@@ -1,6 +1,14 @@
module SnaptradeAccount::DataHelpers
extend ActiveSupport::Concern
+ HELD_ROW_SECURITY_ID_SQL = "holdings.security_id".freeze
+ PROVIDER_ROW_SECURITY_ID_SQL = <<~SQL.squish.freeze
+ CASE WHEN holdings.security_locked
+ THEN COALESCE(holdings.provider_security_id, holdings.security_id)
+ ELSE holdings.security_id
+ END
+ SQL
+
private
# Convert SnapTrade SDK objects to hashes
@@ -56,11 +64,17 @@ module SnaptradeAccount::DataHelpers
nil
end
- def resolve_security(symbol, symbol_data)
+ # A ticker can have several Security rows (one per exchange), so the
+ # lookup must be deterministic or a holding flips between rows from one
+ # sync to the next (#3988). Order: the row the account already holds, the
+ # row on SnapTrade's reported exchange, then a fixed preference order.
+ #
+ # provider_row: true is for holdings; see held_security_for.
+ def resolve_security(symbol, symbol_data, account: nil, account_provider_id: nil, provider_row: false)
ticker = symbol.to_s.upcase.strip
return nil if ticker.blank?
- security = Security.find_by(ticker: ticker)
+ security = existing_security_for(ticker, symbol_data, account, account_provider_id, provider_row)
# If security exists but has a bad name (looks like a hash), update it
if security && security.name&.start_with?("{")
@@ -85,7 +99,92 @@ module SnaptradeAccount::DataHelpers
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique => e
# Handle race condition - another process may have created it
Rails.logger.error "Failed to create security #{ticker}: #{e.message}"
- Security.find_by(ticker: ticker) # Retry find in case of race condition
+ existing_security_for(ticker, symbol_data, account, account_provider_id, provider_row) # Retry find in case of race condition
+ end
+
+ def existing_security_for(ticker, symbol_data, account, account_provider_id, provider_row = false)
+ held_security_for(account, ticker, account_provider_id, provider_row: provider_row) ||
+ reported_exchange_security_for(ticker, symbol_data) ||
+ preferred_security_for(ticker, symbol_data, account, account_provider_id)
+ end
+
+ # The row the position currently sits on, so it never moves. That includes
+ # a same-ticker remap: SnapTrade sends no external_id, so the import
+ # adapter's provider_security fallbacks never run for it. Latest date
+ # wins, provider holdings first.
+ #
+ # Only SnapTrade's own holdings and those with no provider (materialized
+ # from the account's trades). Without an external_id the adapter matches
+ # on security, date and currency alone, so following another provider's
+ # holding onto its row would overwrite that provider's quantity.
+ #
+ # With provider_row: true, a holding the user remapped (security_locked)
+ # answers with the row SnapTrade sent (provider_security_id), matched on
+ # that row's ticker. Holdings need it: the import adapter carries a remap
+ # and a locked cost basis to a new day's row by finding the earlier row
+ # whose provider_security_id is the security it is given. Trades must not
+ # use it, because a remap moves the position's trades to the chosen row.
+ def held_security_for(account, ticker, account_provider_id, provider_row: false)
+ return nil unless account
+
+ security_id_sql = provider_row ? PROVIDER_ROW_SECURITY_ID_SQL : HELD_ROW_SECURITY_ID_SQL
+
+ security_id = account.holdings
+ .where(account_provider_id: [ account_provider_id, nil ].uniq)
+ .joins(Arel.sql("INNER JOIN securities ON securities.id = #{security_id_sql}"))
+ .where("UPPER(securities.ticker) = ?", ticker)
+ .order(date: :desc)
+ .order(Arel.sql("holdings.account_provider_id IS NULL"), :id)
+ .pick(Arel.sql(security_id_sql))
+
+ security_id && Security.find_by(id: security_id)
+ end
+
+ def reported_exchange_security_for(ticker, symbol_data)
+ exchange = extract_exchange(symbol_data)
+ return nil if exchange.blank?
+
+ # Rows SnapTrade created carry its exchange in exchange_mic, not
+ # exchange_operating_mic, so they need a second match.
+ Security.find_by_ticker_and_exchange(ticker: ticker, exchange_operating_mic: exchange) ||
+ Security.where("UPPER(ticker) = ?", ticker).where(exchange_mic: exchange).order(:created_at, :id).first
+ end
+
+ # Not an identity match: the rows differ by exchange, and this order says
+ # nothing about which market SnapTrade trades. Once picked, the held
+ # position keeps the pick, so a wrong one never corrects itself; record
+ # each ambiguous pick so support can find the affected accounts.
+ def preferred_security_for(ticker, symbol_data, account, account_provider_id)
+ candidates = Security.where("UPPER(ticker) = ?", ticker)
+ .order(:offline, Arel.sql("price_provider IS NULL"), :created_at, :id)
+ .to_a
+
+ if candidates.size > 1
+ capture_ambiguous_security(ticker, candidates, symbol_data, account, account_provider_id)
+ end
+
+ candidates.first
+ end
+
+ def capture_ambiguous_security(ticker, candidates, symbol_data, account, account_provider_id)
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "warn",
+ message: "Resolved #{ticker} to one of #{candidates.size} securities by fallback order; " \
+ "no held position and no row on the reported exchange",
+ source: self.class.name,
+ provider_key: "snaptrade",
+ account: account,
+ account_provider_id: account_provider_id,
+ metadata: {
+ ticker: ticker,
+ reported_exchange: extract_exchange(symbol_data),
+ chosen_security_id: candidates.first.id,
+ candidates: candidates.map do |security|
+ security.slice(:id, :exchange_operating_mic, :exchange_mic, :offline, :price_provider)
+ end
+ }
+ )
end
def extract_security_name(symbol_data, fallback_ticker)
diff --git a/app/models/snaptrade_account/holdings_processor.rb b/app/models/snaptrade_account/holdings_processor.rb
index f38b5b3b5e..a1a71aec96 100644
--- a/app/models/snaptrade_account/holdings_processor.rb
+++ b/app/models/snaptrade_account/holdings_processor.rb
@@ -97,7 +97,9 @@ class SnaptradeAccount::HoldingsProcessor
Rails.logger.info "SnaptradeAccount::HoldingsProcessor - Processing holding for ticker: #{ticker}"
# Resolve or create the security
- security = resolve_security(ticker, symbol_data)
+ # The provider's own row, so the import adapter can carry a user's remap
+ # and cost-basis lock forward; it returns the row the holding is on.
+ security = resolve_security(ticker, symbol_data, account: account, account_provider_id: @snaptrade_account.account_provider&.id, provider_row: true)
return unless security
# Parse values
@@ -118,7 +120,7 @@ class SnaptradeAccount::HoldingsProcessor
Rails.logger.info "SnaptradeAccount::HoldingsProcessor - Importing holding: #{ticker} qty=#{quantity} price=#{price} currency=#{currency}"
# Import the holding via the adapter
- import_adapter.import_holding(
+ holding = import_adapter.import_holding(
security: security,
quantity: quantity,
amount: amount,
@@ -136,7 +138,7 @@ class SnaptradeAccount::HoldingsProcessor
avg_price = data["average_purchase_price"] || data[:average_purchase_price] ||
data["cost_basis"] || data[:cost_basis]
if avg_price.present?
- update_holding_cost_basis(security, avg_price)
+ update_holding_cost_basis(holding&.security || security, avg_price)
end
end
diff --git a/test/models/snaptrade_account/activities_processor_test.rb b/test/models/snaptrade_account/activities_processor_test.rb
index e7567f576e..c441f3bac5 100644
--- a/test/models/snaptrade_account/activities_processor_test.rb
+++ b/test/models/snaptrade_account/activities_processor_test.rb
@@ -1053,6 +1053,35 @@ class SnaptradeAccount::ActivitiesProcessorTest < ActiveSupport::TestCase
assert_equal 0, Entry.where(external_id: "trade_orphan").count
end
+ test "a trade resolves to the security the account already holds when its ticker has duplicate rows" do
+ held = Security.create!(ticker: "DUPT", name: "Held row")
+ Security.create!(ticker: "DUPT", name: "Priced row", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+ @account.holdings.create!(
+ security: held, date: 1.day.ago.to_date, qty: 10, price: 100, amount: 1000, currency: "USD",
+ account_provider_id: @snaptrade_account.account_provider&.id
+ )
+ held.update!(name: "Held row (renamed)")
+
+ process_activities(build_trade_activity(id: "dup_trade", type: "BUY", symbol: "DUPT", units: 1, price: 100))
+
+ assert_equal held, snaptrade_entry("dup_trade").entryable.security
+ end
+
+ # A remap moves the position's trades to the row the user chose, so a new
+ # trade must land there too, not on the provider's original row.
+ test "a trade for a remapped position lands on the row the user chose" do
+ original = Security.create!(ticker: "DUPT2", name: "SnapTrade row")
+ listed = Security.create!(ticker: "DUPT2", name: "Listed row", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+ @account.holdings.create!(
+ security: original, date: 1.day.ago.to_date, qty: 10, price: 100, amount: 1000, currency: "USD",
+ account_provider_id: @snaptrade_account.account_provider&.id
+ ).remap_security!(listed)
+
+ process_activities(build_trade_activity(id: "remapped_trade", type: "BUY", symbol: "DUPT2", units: 1, price: 100))
+
+ assert_equal listed, snaptrade_entry("remapped_trade").entryable.security
+ end
+
# Modeled on real Fidelity option buy activity (TQQQ call) where symbol is nil
test "processes option buy trade when symbol is nil and option_symbol is present" do
process_activities(
diff --git a/test/models/snaptrade_account/holdings_processor_test.rb b/test/models/snaptrade_account/holdings_processor_test.rb
new file mode 100644
index 0000000000..59b63c29b2
--- /dev/null
+++ b/test/models/snaptrade_account/holdings_processor_test.rb
@@ -0,0 +1,178 @@
+require "test_helper"
+
+class SnaptradeAccount::HoldingsProcessorTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @snaptrade_account = snaptrade_accounts(:fidelity_401k)
+
+ @account = @family.accounts.create!(
+ name: "Test Investment",
+ balance: 50000,
+ cash_balance: 1000,
+ currency: "USD",
+ accountable: Investment.new
+ )
+
+ @snaptrade_account.ensure_account_provider!(@account)
+ @snaptrade_account.reload
+ end
+
+ test "a held position stays on its security across syncs when the ticker has duplicate rows" do
+ held = Security.create!(ticker: "DUPH", name: "Held row")
+ # The row the ordered fallback would prefer, so only the held-position step keeps the holding on `held`.
+ Security.create!(ticker: "DUPH", name: "Priced row", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+ hold_position(held, date: 1.day.ago.to_date)
+
+ # Rewriting the held row moves its tuple behind the other one, so an unordered lookup reads the other row first.
+ held.update!(name: "Held row (renamed)")
+
+ 2.times do
+ process_holdings(build_holding(symbol: "DUPH"))
+ assert_equal [ held.id ], @account.holdings.where(date: Date.current).pluck(:security_id)
+ end
+ end
+
+ test "a security created on one sync is the one the next sync resolves after a duplicate row appears" do
+ process_holdings(build_holding(symbol: "DUPN"))
+ created = Security.find_by!(ticker: "DUPN")
+
+ # A second row for the ticker arrives later, for example from a CSV import.
+ Security.create!(ticker: "DUPN", name: "Imported row", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+ created.update!(name: "Created row (renamed)")
+
+ # Age the first sync's holding so the next sync writes a new one.
+ @account.holdings.where(date: Date.current).update_all(date: 1.day.ago.to_date)
+ process_holdings(build_holding(symbol: "DUPN"))
+
+ assert_equal [ created.id ], @account.holdings.where(date: Date.current).pluck(:security_id)
+ end
+
+ # Another provider on the same account holds the ticker today on another
+ # row. SnapTrade's holding goes on the row for the exchange it reports, and
+ # the other provider's holding keeps its quantity and its provider.
+ test "a sync leaves another provider's holding of the same ticker alone" do
+ item = @family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ other_provider = AccountProvider.create!(account: @account, provider: item.coinstats_accounts.create!(name: "Other provider", currency: "USD"))
+ theirs = Security.create!(ticker: "DUPO", name: "Other provider's row")
+ listed = Security.create!(ticker: "DUPO", name: "Listed row", exchange_operating_mic: "XNYS")
+ theirs_holding = @account.holdings.create!(security: theirs, date: Date.current, qty: 3, price: 100, amount: 300,
+ currency: "USD", account_provider: other_provider)
+
+ process_holdings(build_holding(symbol: "DUPO").deep_merge("instrument" => { "exchange" => "XNYS" }))
+
+ theirs_holding.reload
+ assert_equal [ 3, other_provider.id ], [ theirs_holding.qty, theirs_holding.account_provider_id ]
+ assert_equal 10, @account.holdings.find_by!(security: listed, date: Date.current).qty
+ end
+
+ test "an ambiguous fallback pick is logged against this connection" do
+ older = Security.create!(ticker: "DUPF", name: "Dup F", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+ Security.create!(ticker: "DUPF", name: "Dup F", exchange_operating_mic: "XNAS", price_provider: "yahoo_finance")
+
+ assert_difference -> { DebugLogEntry.count }, 1 do
+ process_holdings(build_holding(symbol: "DUPF"))
+ end
+
+ entry = DebugLogEntry.order(:created_at).last
+ assert_equal [ "SnaptradeAccount::HoldingsProcessor", @family, @snaptrade_account.account_provider ],
+ [ entry.source, entry.family, entry.account_provider ]
+ assert_equal [ older.id ], @account.holdings.where(date: Date.current).pluck(:security_id)
+ end
+
+ # The import adapter carries a remap and a cost-basis lock forward to the
+ # next day's row by finding the earlier row whose provider_security_id is
+ # the security it is given, so a remapped position must be resolved to the
+ # provider's original row, not the row the user moved it to.
+ test "a same-ticker remap stays locked on the next day's holding" do
+ original, listed = remap_to_listed_row("DUPR")
+
+ process_holdings(build_holding(symbol: "DUPR"))
+
+ today = @account.holdings.where(date: Date.current).to_a
+ assert_equal [ listed.id ], today.map(&:security_id)
+ assert today.first.security_locked?
+ assert_equal original.id, today.first.provider_security_id
+ end
+
+ test "a remapped position's locked cost basis is carried to the next day's holding" do
+ _original, listed = remap_to_listed_row("DUPC")
+ @account.holdings.find_by!(date: 1.day.ago.to_date).set_manual_cost_basis!(BigDecimal("42"))
+
+ process_holdings(build_holding(symbol: "DUPC").merge("average_purchase_price" => 90))
+
+ today = @account.holdings.find_by!(date: Date.current)
+ assert_equal listed, today.security
+ assert today.cost_basis_locked?
+ assert_equal BigDecimal("42"), today.cost_basis
+ end
+
+ # The provider's cost basis is written to the row the holding landed on.
+ test "a remapped position's holding still takes the provider's cost basis" do
+ _original, listed = remap_to_listed_row("DUPB")
+
+ process_holdings(build_holding(symbol: "DUPB").merge("average_purchase_price" => 90))
+
+ today = @account.holdings.find_by!(date: Date.current)
+ assert_equal listed, today.security
+ assert_equal BigDecimal("90"), today.cost_basis
+ assert_equal "provider", today.cost_basis_source
+ end
+
+ # A remap to a row of another ticker: the position's holdings no longer
+ # carry SnapTrade's ticker, so only the provider's original row links them.
+ # A second row of the original ticker, preferred by the fallback order,
+ # must not take the next day's holding.
+ test "a remap to another ticker stays locked on the next day's holding" do
+ process_holdings(build_holding(symbol: "DUPX"))
+ original = Security.find_by!(ticker: "DUPX")
+ Security.create!(ticker: "DUPX", name: "Priced row", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+ other_ticker = Security.create!(ticker: "DUPY", name: "Other ticker", exchange_operating_mic: "XNAS")
+ @account.holdings.where(date: Date.current).update_all(date: 1.day.ago.to_date)
+ @account.holdings.find_by!(security: original).remap_security!(other_ticker)
+
+ process_holdings(build_holding(symbol: "DUPX"))
+
+ today = @account.holdings.where(date: Date.current).to_a
+ assert_equal [ other_ticker.id ], today.map(&:security_id)
+ assert today.first.security_locked?
+ assert_equal original.id, today.first.provider_security_id
+ end
+
+ private
+ # Yesterday's sync put the position on the row SnapTrade created; the
+ # user then remapped it to a listed row of the same ticker.
+ def remap_to_listed_row(ticker)
+ process_holdings(build_holding(symbol: ticker))
+ original = Security.find_by!(ticker: ticker)
+ listed = Security.create!(ticker: ticker, name: "Listed row", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+ @account.holdings.where(date: Date.current).update_all(date: 1.day.ago.to_date)
+ @account.holdings.find_by!(security: original).remap_security!(listed)
+ [ original, listed ]
+ end
+
+ def hold_position(security, date:)
+ @account.holdings.create!(
+ security: security,
+ date: date,
+ qty: 10,
+ price: 100,
+ amount: 1000,
+ currency: "USD",
+ account_provider_id: @snaptrade_account.account_provider&.id
+ )
+ end
+
+ def process_holdings(*holdings)
+ @snaptrade_account.update!(raw_holdings_payload: holdings)
+ SnaptradeAccount::HoldingsProcessor.new(@snaptrade_account).process
+ end
+
+ def build_holding(symbol:, units: 10, price: 100)
+ {
+ "instrument" => { "symbol" => symbol, "description" => "#{symbol} Inc" },
+ "units" => units,
+ "price" => price,
+ "currency" => { "code" => "USD" }
+ }
+ end
+end
diff --git a/test/models/snaptrade_data_helpers_test.rb b/test/models/snaptrade_data_helpers_test.rb
index 86eead9a1b..806031bcde 100644
--- a/test/models/snaptrade_data_helpers_test.rb
+++ b/test/models/snaptrade_data_helpers_test.rb
@@ -14,8 +14,8 @@ class SnaptradeDataHelpersTest < ActiveSupport::TestCase
parse_date(value)
end
- def test_resolve_security(symbol, symbol_data)
- resolve_security(symbol, symbol_data)
+ def test_resolve_security(symbol, symbol_data, account: nil, account_provider_id: nil, provider_row: false)
+ resolve_security(symbol, symbol_data, account: account, account_provider_id: account_provider_id, provider_row: provider_row)
end
def test_extract_currency(data, symbol_data = {}, fallback = nil)
@@ -146,6 +146,233 @@ class SnaptradeDataHelpersTest < ActiveSupport::TestCase
assert_equal "RACECOND", result.ticker
end
+ test "resolve_security prefers the row on the exchange SnapTrade reports, whichever was created first" do
+ xnys_first = Security.create!(ticker: "DUPA", name: "Dup A", exchange_operating_mic: "XNYS")
+ Security.create!(ticker: "DUPA", name: "Dup A")
+ Security.create!(ticker: "DUPB", name: "Dup B")
+ xnys_last = Security.create!(ticker: "DUPB", name: "Dup B", exchange_operating_mic: "XNYS")
+
+ symbol_data = { "exchange" => { "mic_code" => "XNYS" } }
+
+ assert_equal xnys_first, @helper.test_resolve_security("DUPA", symbol_data)
+ assert_equal xnys_last, @helper.test_resolve_security("DUPB", symbol_data)
+ end
+
+ test "resolve_security without an exchange prefers an online priced row over an older unpriced one" do
+ Security.create!(ticker: "DUPC", name: "Dup C", exchange_operating_mic: "XASX", offline: true)
+ Security.create!(ticker: "DUPC", name: "Dup C", exchange_operating_mic: "XNAS")
+ priced = Security.create!(ticker: "DUPC", name: "Dup C", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+
+ assert_equal priced, @helper.test_resolve_security("DUPC", {})
+ end
+
+ test "resolve_security leaves a different ticker alone when another ticker has duplicates" do
+ Security.create!(ticker: "DUPD", name: "Dup D")
+ Security.create!(ticker: "DUPD", name: "Dup D", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+ other = Security.create!(ticker: "SOLO", name: "Solo")
+
+ assert_equal other, @helper.test_resolve_security("SOLO", { "exchange" => { "mic_code" => "XNYS" } })
+ end
+
+ test "resolve_security race retry picks the same row as the ordered lookup" do
+ priced = nil
+ Security.define_singleton_method(:create!) do |*|
+ # Another process creates both rows between the lookup and the create.
+ Security.new(ticker: "RACEDUP", name: "Unpriced").save!
+ priced = Security.new(ticker: "RACEDUP", name: "Priced", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance").tap(&:save!)
+ raise ActiveRecord::RecordNotUnique
+ end
+
+ result = @helper.test_resolve_security("RACEDUP", {})
+
+ assert_not_nil priced
+ assert_equal priced, result
+ ensure
+ Security.singleton_class.send(:remove_method, :create!)
+ end
+
+ test "resolve_security race retry still prefers the row on the reported exchange" do
+ reported = nil
+ Security.define_singleton_method(:create!) do |*|
+ Security.new(ticker: "RACEMIC", name: "Priced", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance").save!
+ reported = Security.new(ticker: "RACEMIC", name: "Reported", exchange_operating_mic: "XNAS").tap(&:save!)
+ raise ActiveRecord::RecordNotUnique
+ end
+
+ result = @helper.test_resolve_security("RACEMIC", { "exchange" => { "mic_code" => "XNAS" } })
+
+ assert_not_nil reported
+ assert_equal reported, result
+ ensure
+ Security.singleton_class.send(:remove_method, :create!)
+ end
+
+ test "resolve_security matches a row SnapTrade created on the reported exchange" do
+ Security.create!(ticker: "DUPS", name: "Other exchange", exchange_operating_mic: "XASX", price_provider: "yahoo_finance")
+ snaptrade_row = Security.create!(ticker: "DUPS", name: "SnapTrade row", exchange_mic: "XNYS")
+
+ assert_equal snaptrade_row, @helper.test_resolve_security("DUPS", { "exchange" => { "mic_code" => "XNYS" } })
+ end
+
+ test "resolve_security follows the account's latest holding when its position already moved rows" do
+ account = accounts(:investment)
+ earlier = Security.create!(ticker: "DUPL", name: "Earlier row", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+ latest = Security.create!(ticker: "DUPL", name: "Latest row")
+ hold(account, earlier, date: 2.days.ago.to_date)
+ hold(account, latest, date: 1.day.ago.to_date)
+
+ assert_equal latest, @helper.test_resolve_security("DUPL", {}, account: account)
+ end
+
+ test "resolve_security keeps a holding the user remapped to another row of the same ticker" do
+ account = accounts(:investment)
+ provider_row = Security.create!(ticker: "DUPR", name: "Provider row")
+ remapped_to = Security.create!(ticker: "DUPR", name: "Remapped row", exchange_operating_mic: "XNYS")
+ hold(account, remapped_to, date: 1.day.ago.to_date, provider_security: provider_row)
+
+ assert_equal remapped_to, @helper.test_resolve_security("DUPR", {}, account: account)
+ end
+
+ # Holdings ask for the provider's row of a locked remap, so the import
+ # adapter can carry the lock to the next day's row; trades keep the row
+ # the user chose, where the remap moved the position's trades.
+ test "resolve_security answers a locked remap with the provider's row only when asked" do
+ account = accounts(:investment)
+ provider_row = Security.create!(ticker: "DUPK", name: "Provider row")
+ remapped_to = Security.create!(ticker: "DUPK", name: "Remapped row", exchange_operating_mic: "XNYS")
+ hold(account, remapped_to, date: 1.day.ago.to_date, provider_security: provider_row).update!(security_locked: true)
+
+ assert_equal remapped_to, @helper.test_resolve_security("DUPK", {}, account: account)
+ assert_equal provider_row, @helper.test_resolve_security("DUPK", {}, account: account, provider_row: true)
+ end
+
+ # Only a lock says the user chose the row. An unlocked holding that still
+ # names another provider row is followed where it sits.
+ test "resolve_security follows an unlocked holding even when asked for the provider's row" do
+ account = accounts(:investment)
+ provider_row = Security.create!(ticker: "DUPU", name: "Provider row")
+ held = Security.create!(ticker: "DUPU", name: "Held row", exchange_operating_mic: "XNYS")
+ hold(account, held, date: 1.day.ago.to_date, provider_security: provider_row)
+
+ assert_equal held, @helper.test_resolve_security("DUPU", {}, account: account, provider_row: true)
+ end
+
+ test "resolve_security race retry still answers a locked remap with the provider's row" do
+ account = accounts(:investment)
+ provider_row = nil
+ Security.define_singleton_method(:create!) do |*|
+ # Another sync creates the rows and the user's remap between the lookup and the create.
+ provider_row = Security.new(ticker: "RACEK", name: "Provider row").tap(&:save!)
+ remapped_to = Security.new(ticker: "RACEK", name: "Remapped row", exchange_operating_mic: "XNYS").tap(&:save!)
+ account.holdings.create!(security: remapped_to, provider_security: provider_row, security_locked: true,
+ date: 1.day.ago.to_date, qty: 1, price: 100, amount: 100, currency: "USD")
+ raise ActiveRecord::RecordNotUnique
+ end
+
+ result = @helper.test_resolve_security("RACEK", {}, account: account, provider_row: true)
+
+ assert_not_nil provider_row
+ assert_equal provider_row, result
+ ensure
+ Security.singleton_class.send(:remove_method, :create!)
+ end
+
+ # Another provider linked to the same account can hold the same ticker on
+ # another row. Without an external_id the import adapter matches holdings by
+ # security, date and currency alone, so following that holding would make
+ # SnapTrade overwrite it.
+ test "resolve_security does not follow another provider's holding" do
+ account = accounts(:investment)
+ snaptrade = AccountProvider.create!(account: account, provider: snaptrade_accounts(:fidelity_401k))
+ other = AccountProvider.create!(account: account, provider: other_provider_account)
+ theirs = Security.create!(ticker: "DUPO", name: "Other provider's row", exchange_operating_mic: "XNAS")
+ ours = Security.create!(ticker: "DUPO", name: "SnapTrade's row")
+ hold(account, ours, date: 3.days.ago.to_date, account_provider: snaptrade)
+ hold(account, theirs, date: 1.day.ago.to_date, account_provider: other)
+
+ assert_equal ours, @helper.test_resolve_security("DUPO", {}, account: account, account_provider_id: snaptrade.id)
+ end
+
+ # Holdings materialized from the account's trades carry no provider, and a
+ # remap there is the user's choice, so they still count.
+ test "resolve_security still follows a holding with no provider" do
+ account = accounts(:investment)
+ snaptrade = AccountProvider.create!(account: account, provider: snaptrade_accounts(:fidelity_401k))
+ Security.create!(ticker: "DUPM", name: "Priced row", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+ materialized = Security.create!(ticker: "DUPM", name: "Materialized row")
+ hold(account, materialized, date: 1.day.ago.to_date)
+
+ assert_equal materialized, @helper.test_resolve_security("DUPM", {}, account: account, account_provider_id: snaptrade.id)
+ end
+
+ # The last tier has no identity signal: with no held position and no row on
+ # SnapTrade's reported exchange, two online, priced rows for different
+ # markets are told apart only by age. This documents that known limit, and
+ # that the pick is recorded for support rather than made silently.
+ test "resolve_security picks the older of two priced rows differing only by exchange, and logs it" do
+ account = accounts(:investment)
+ snaptrade = AccountProvider.create!(account: account, provider: snaptrade_accounts(:fidelity_401k))
+ older = Security.create!(ticker: "DUPX", name: "Dup X", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+ newer = Security.create!(ticker: "DUPX", name: "Dup X", exchange_operating_mic: "XNAS", price_provider: "yahoo_finance")
+ # Rewriting the older row moves its tuple behind the newer one.
+ older.update!(name: "Dup X (renamed)")
+
+ assert_difference -> { DebugLogEntry.count }, 2 do
+ 2.times { assert_equal older, @helper.test_resolve_security("DUPX", {}, account: account, account_provider_id: snaptrade.id) }
+ end
+
+ entry = DebugLogEntry.order(:created_at).last
+ assert_equal [ "provider_sync", "warn", "snaptrade", TestHelper.name ],
+ [ entry.category, entry.level, entry.provider_key, entry.source ]
+ assert_equal [ account.family, account, snaptrade ], [ entry.family, entry.account, entry.account_provider ]
+ assert_equal "DUPX", entry.metadata["ticker"]
+ assert_equal older.id, entry.metadata["chosen_security_id"]
+ assert_equal [ older.id, newer.id ], entry.metadata["candidates"].map { |c| c["id"] }
+ assert_equal [ "XNYS", "XNAS" ], entry.metadata["candidates"].map { |c| c["exchange_operating_mic"] }
+ end
+
+ test "resolve_security logs a fallback pick when the reported exchange matches no row, and without an account" do
+ older = Security.create!(ticker: "DUPU", name: "Dup U", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+ Security.create!(ticker: "DUPU", name: "Dup U", exchange_operating_mic: "XNAS", price_provider: "yahoo_finance")
+
+ assert_difference -> { DebugLogEntry.count }, 1 do
+ assert_equal older, @helper.test_resolve_security("DUPU", { "exchange" => { "mic_code" => "XTSE" } })
+ end
+
+ entry = DebugLogEntry.order(:created_at).last
+ assert_equal "XTSE", entry.metadata["reported_exchange"]
+ assert_nil entry.family
+ assert_nil entry.account_provider
+ end
+
+ test "resolve_security does not log when the ticker has a single row" do
+ only = Security.create!(ticker: "ONLY", name: "Only row", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+
+ assert_no_difference -> { DebugLogEntry.count } do
+ assert_equal only, @helper.test_resolve_security("ONLY", {})
+ end
+ end
+
+ test "resolve_security does not log when the held position decides" do
+ account = accounts(:investment)
+ Security.create!(ticker: "DUPHL", name: "Priced row", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+ held = Security.create!(ticker: "DUPHL", name: "Held row", exchange_operating_mic: "XNAS", price_provider: "yahoo_finance")
+ hold(account, held, date: 1.day.ago.to_date)
+
+ assert_no_difference -> { DebugLogEntry.count } do
+ assert_equal held, @helper.test_resolve_security("DUPHL", {}, account: account)
+ end
+ end
+
+ test "resolve_security does not log when the reported exchange decides" do
+ Security.create!(ticker: "DUPE", name: "Dup E", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
+ reported = Security.create!(ticker: "DUPE", name: "Dup E", exchange_operating_mic: "XNAS", price_provider: "yahoo_finance")
+
+ assert_no_difference -> { DebugLogEntry.count } do
+ assert_equal reported, @helper.test_resolve_security("DUPE", { "exchange" => { "mic_code" => "XNAS" } })
+ end
+ end
+
# === extract_currency tests ===
test "extract_currency handles hash with code key (symbol access)" do
@@ -184,4 +411,18 @@ class SnaptradeDataHelpersTest < ActiveSupport::TestCase
result = @helper.test_extract_currency(data, {}, nil)
assert_nil result
end
+
+ private
+
+ def hold(account, security, date:, provider_security: nil, account_provider: nil)
+ account.holdings.create!(
+ security: security, provider_security: provider_security, date: date,
+ qty: 1, price: 100, amount: 100, currency: "USD", account_provider: account_provider
+ )
+ end
+
+ def other_provider_account
+ item = families(:dylan_family).coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ item.coinstats_accounts.create!(name: "Other provider", currency: "USD")
+ end
end