The personal finance app for everyone (by everyone)
Ruby
fix(snaptrade): trust reported trade amount and import trade fees (#3507)
Justin McBride5a198fb92822
diff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rbindex 0753a475d8..28388e1018 100644--- a/app/models/account/provider_import_adapter.rb+++ b/app/models/account/provider_import_adapter.rb@@ -627,7 +627,7 @@ class Account::ProviderImportAdapter# @param security [Security] The security object# @param quantity [BigDecimal, Numeric] Number of shares (negative for sells, positive for buys)# @param price [BigDecimal, Numeric] Price per share- # @param amount [BigDecimal, Numeric] Total trade value+ # @param amount [BigDecimal, Numeric] Total cash impact of the trade, fee included# @param currency [String] Currency code# @param date [Date, String] Trade date# @param name [String, nil] Optional custom name for the trade@@ -635,8 +635,9 @@ class Account::ProviderImportAdapter# @param source [String] Provider name# @param activity_label [String, nil] Investment activity label (e.g., "Buy", "Sell", "Reinvestment")# @param exchange_rate [BigDecimal, Numeric, nil] Optional provider-supplied FX rate into the account currency+ # @param fee [BigDecimal, Numeric, nil] Optional provider-reported transaction fee, already included in `amount`# @return [Entry] The created entry with trade- def import_trade(security:, quantity:, price:, amount:, currency:, date:, name: nil, external_id: nil, source:, activity_label: nil, exchange_rate: nil)+ def import_trade(security:, quantity:, price:, amount:, currency:, date:, name: nil, external_id: nil, source:, activity_label: nil, exchange_rate: nil, fee: nil)raise ArgumentError, "security is required" if security.nil?raise ArgumentError, "source is required" if source.blank?@@ -677,6 +678,7 @@ class Account::ProviderImportAdapterinvestment_activity_label: activity_label || (quantity > 0 ? "Buy" : "Sell")}trade_attributes[:exchange_rate] = exchange_rate unless exchange_rate.nil?+ trade_attributes[:fee] = fee unless fee.nil?entry.entryable.assign_attributes(trade_attributes)diff --git a/app/models/snaptrade_account/activities_processor.rb b/app/models/snaptrade_account/activities_processor.rbindex bcce376296..8d8f6b9fb5 100644--- a/app/models/snaptrade_account/activities_processor.rb+++ b/app/models/snaptrade_account/activities_processor.rb@@ -60,8 +60,18 @@ class SnaptradeAccount::ActivitiesProcessoractivities_data.each do |activity_data|process_activity(activity_data.with_indifferent_access)rescue => e- Rails.logger.error "SnaptradeAccount::ActivitiesProcessor - Failed to process activity: #{e.message}"- Rails.logger.error e.backtrace.first(5).join("\n") if e.backtrace+ activity = activity_data.is_a?(Hash) ? activity_data.with_indifferent_access : {}+ capture_debug_log(+ category: "provider_sync_error",+ level: "error",+ message: "Failed to process activity #{activity[:id]}: #{e.message}",+ metadata: {+ activity_id: activity[:id]&.to_s,+ activity_type: activity[:type],+ error_class: e.class.name,+ backtrace: e.backtrace&.first(5)+ }+ )end{ trades: @trades_count, transactions: @transactions_count }@@ -77,6 +87,27 @@ class SnaptradeAccount::ActivitiesProcessor@import_adapter ||= Account::ProviderImportAdapter.new(account)end+ # Support-relevant events go to /settings/debug rather than the Rails log+ def capture_debug_log(message:, category: "provider_sync", level: "warn", metadata: {})+ DebugLogEntry.capture(+ category: category,+ level: level,+ message: message,+ source: self.class.name,+ provider_key: "snaptrade",+ family: @snaptrade_account.snaptrade_item.family,+ account_provider: @snaptrade_account.account_provider,+ metadata: { snaptrade_account_id: @snaptrade_account.id }.merge(metadata)+ )+ end++ def capture_skipped_trade(reason, description, external_id:, activity_type:, ticker: nil)+ capture_debug_log(+ message: "Skipping trade #{external_id}: #{description}",+ metadata: { activity_id: external_id, activity_type: activity_type, ticker: ticker, reason: reason }.compact+ )+ end+def process_activity(data)# Ensure we have indifferent accessdata = data.with_indifferent_access if data.is_a?(Hash)@@ -131,21 +162,29 @@ class SnaptradeAccount::ActivitiesProcessor# Must have a symbol for tradesif ticker.blank?- Rails.logger.warn "SnaptradeAccount::ActivitiesProcessor - Skipping trade without symbol: #{external_id}"+ capture_skipped_trade("missing_symbol", "no symbol", external_id: external_id, activity_type: activity_type)returnend# Resolve securitysecurity = resolve_security(ticker, symbol_data)- return unless security+ unless security+ capture_skipped_trade("unresolved_security", "security could not be resolved",+ external_id: external_id, activity_type: activity_type, ticker: ticker)+ return+ end# Parse trade valuesquantity = parse_decimal(data[:units]) || parse_decimal(data["units"]) ||parse_decimal(data[:quantity]) || parse_decimal(data["quantity"])price = parse_decimal(data[:price]) || parse_decimal(data["price"])+ amount = parse_decimal(data[:amount]) || parse_decimal(data["amount"]) ||+ parse_decimal(data[:trade_value]) || parse_decimal(data["trade_value"])+ fee = (parse_decimal(data[:fee]) || parse_decimal(data["fee"]))&.absif quantity.nil?- Rails.logger.warn "SnaptradeAccount::ActivitiesProcessor - Skipping trade without quantity: #{external_id}"+ capture_skipped_trade("missing_quantity", "no quantity",+ external_id: external_id, activity_type: activity_type, ticker: ticker)returnend@@ -156,19 +195,38 @@ class SnaptradeAccount::ActivitiesProcessorquantity.absend- # Calculate amount- amount = if price- quantity * price- else- parse_decimal(data[:amount]) || parse_decimal(data["amount"]) ||- parse_decimal(data[:trade_value]) || parse_decimal(data["trade_value"])+ amount = if amount&.nonzero?+ quantity.negative? ? -amount.abs : amount.abs+ elsif price+ # Same convention as a manually entered trade: the fee adds to a buy's+ # cost and comes out of a sell's proceeds.+ quantity * price + (fee || 0)endif amount.nil?- Rails.logger.warn "SnaptradeAccount::ActivitiesProcessor - Skipping trade without amount: #{external_id}"+ capture_skipped_trade("missing_amount", "no amount, and no price to derive it from",+ external_id: external_id, activity_type: activity_type, ticker: ticker)returnend+ if price.nil? && !quantity.zero?+ price = (amount - (fee || 0)) / quantity+ capture_debug_log(+ level: "info",+ message: "Derived missing price for trade #{external_id} from its amount and quantity",+ metadata: {+ activity_id: external_id,+ activity_type: activity_type,+ ticker: ticker,+ reason: "derived_price",+ quantity: quantity.to_s("F"),+ amount: amount.to_s("F"),+ fee: fee&.to_s("F"),+ derived_price: price.to_s("F")+ }.compact+ )+ end+# Get the activity dateactivity_date = parse_date(data[:settlement_date]) || parse_date(data["settlement_date"]) ||parse_date(data[:trade_date]) || parse_date(data["trade_date"]) || Date.current@@ -185,7 +243,7 @@ class SnaptradeAccount::ActivitiesProcessordescription = data[:description] || data["description"] || "#{activity_type} #{ticker}"- Rails.logger.info "SnaptradeAccount::ActivitiesProcessor - Importing trade: #{ticker} qty=#{quantity} price=#{price} date=#{activity_date}"+ Rails.logger.info "SnaptradeAccount::ActivitiesProcessor - Importing trade: #{ticker} qty=#{quantity} price=#{price} amount=#{amount} fee=#{fee} date=#{activity_date}"result = import_adapter.import_trade(external_id: external_id,@@ -193,6 +251,7 @@ class SnaptradeAccount::ActivitiesProcessorquantity: quantity,price: price,amount: amount,+ fee: fee,currency: currency,date: activity_date,name: description,@@ -278,10 +337,10 @@ class SnaptradeAccount::ActivitiesProcessorlabel = SNAPTRADE_TYPE_TO_LABEL[normalized_type]if label.nil? && normalized_type.present?- # Log unmapped activity types for visibility - helps identify new types to add- Rails.logger.warn(- "SnaptradeAccount::ActivitiesProcessor - Unmapped activity type '#{normalized_type}' " \- "for account #{@snaptrade_account.id}. Consider adding to SNAPTRADE_TYPE_TO_LABEL mapping."+ # Record unmapped activity types for visibility - helps identify new types to add+ capture_debug_log(+ message: "Unmapped activity type '#{normalized_type}'. Consider adding to SNAPTRADE_TYPE_TO_LABEL mapping.",+ metadata: { activity_type: normalized_type })enddiff --git a/test/models/account/provider_import_adapter_test.rb b/test/models/account/provider_import_adapter_test.rbindex 8b70fccba5..57ad3c9e6a 100644--- a/test/models/account/provider_import_adapter_test.rb+++ b/test/models/account/provider_import_adapter_test.rb@@ -297,7 +297,8 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCasesecurity: security,quantity: 5,price: 150.00,- amount: 750.00,+ amount: 754.95,+ fee: 4.95,currency: "USD",date: Date.today,source: "plaid"@@ -306,7 +307,8 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCaseassert_kind_of Trade, entry.entryableassert_equal 5, entry.entryable.qtyassert_equal 150.00, entry.entryable.price- assert_equal 750.00, entry.amount+ assert_equal BigDecimal("4.95"), entry.entryable.fee+ assert_equal BigDecimal("754.95"), entry.amountassert_match(/Buy.*5.*shares/i, entry.name)endend@@ -330,6 +332,39 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCaseassert_equal 0.91, entry.entryable.exchange_rateend+ # So user-entered fees aren't erased by syncing from providers that don't report fees+ test "preserves existing trade fee when reimport omits it" do+ investment_account = accounts(:investment)+ adapter = Account::ProviderImportAdapter.new(investment_account)+ aapl = securities(:aapl)++ entry = adapter.import_trade(+ external_id: "plaid_trade_fee_preserved",+ security: aapl,+ quantity: 5,+ price: 150.00,+ amount: 754.95,+ fee: 4.95,+ currency: "USD",+ date: Date.today,+ source: "plaid"+ )++ updated_entry = adapter.import_trade(+ external_id: "plaid_trade_fee_preserved",+ security: aapl,+ quantity: 5,+ price: 150.00,+ amount: 754.95,+ currency: "USD",+ date: Date.today,+ source: "plaid"+ )++ assert_equal entry.id, updated_entry.id+ assert_equal BigDecimal("4.95"), updated_entry.entryable.reload.fee+ end+test "raises error when security is missing for trade import" doexception = assert_raises(ArgumentError) do@adapter.import_trade(diff --git a/test/models/snaptrade_account/activities_processor_test.rb b/test/models/snaptrade_account/activities_processor_test.rbindex b4b8419c05..ac0dd76efc 100644--- a/test/models/snaptrade_account/activities_processor_test.rb+++ b/test/models/snaptrade_account/activities_processor_test.rb@@ -70,6 +70,131 @@ class SnaptradeAccount::ActivitiesProcessorTest < ActiveSupport::TestCaseassert_equal "Sell", trade.investment_activity_labelend+ test "the trade amount, qty, price, and fee reported by SnapTrade are respected" do+ process_activities(+ build_trade_activity(id: "buy_rounded", type: "BUY", symbol: "AAPL", units: 3, price: 33.33, amount: -101.00, fee: 1.00)+ )++ entry = snaptrade_entry("buy_rounded")+ assert_equal BigDecimal("101"), entry.amount+ assert_equal BigDecimal("3"), entry.entryable.qty+ assert_equal BigDecimal("33.33"), entry.entryable.price+ assert_equal BigDecimal("1.00"), entry.entryable.fee+ end++ test "fractional share quantity is stored exactly" do+ process_activities(+ build_trade_activity(id: "buy_fractional", type: "BUY", symbol: "VTI", units: 0.12345678, price: 149.94, amount: -18.51)+ )++ entry = snaptrade_entry("buy_fractional")+ assert_equal BigDecimal("0.12345678"), entry.entryable.qty+ assert_equal BigDecimal("18.51"), entry.amount+ end++ test "trade direction comes from the activity type, not the sign of SnapTrade's amount" do+ process_activities(+ build_trade_activity(id: "buy_positive_amount", type: "BUY", symbol: "AAPL", units: 3, price: 33.33, amount: 100.00),+ build_trade_activity(id: "sell_negative_amount", type: "SELL", symbol: "AAPL", units: 7, price: 14.29, amount: -100.00)+ )++ assert_equal BigDecimal("100"), snaptrade_entry("buy_positive_amount").amount+ assert_equal BigDecimal("-100"), snaptrade_entry("sell_negative_amount").amount+ end++ test "records the trade fee as a cost regardless of the sign SnapTrade gives it" do+ process_activities(+ build_trade_activity(id: "buy_negative_fee", type: "BUY", symbol: "AAPL", units: 10, price: 150.00, amount: -1504.95, fee: -4.95)+ )++ assert_equal BigDecimal("4.95"), snaptrade_entry("buy_negative_fee").entryable.fee+ end++ test "a zero reported amount falls back to qty times price" do+ process_activities(+ build_trade_activity(id: "buy_zero_amount", type: "BUY", symbol: "AAPL", units: 2, price: 50.00, amount: 0)+ )++ assert_equal BigDecimal("100"), snaptrade_entry("buy_zero_amount").amount+ end++ test "when amount is not reported, the fallback amount includes the fee like a manually entered trade" do+ process_activities(+ build_trade_activity(id: "buy_no_amount", type: "BUY", symbol: "AAPL", units: 10, price: 150.00, fee: 4.95),+ build_trade_activity(id: "sell_no_amount", type: "SELL", symbol: "AAPL", units: 10, price: 150.00, fee: 4.95)+ )++ assert_equal BigDecimal("1504.95"), snaptrade_entry("buy_no_amount").amount+ assert_equal BigDecimal("-1495.05"), snaptrade_entry("sell_no_amount").amount+ end++ test "imports the trade with a price derived from amount and units, and creates debug log, when price is missing" do+ process_activities(+ build_trade_activity(id: "buy_no_price", type: "BUY", symbol: "AAPL", units: 4, price: nil, amount: -100.00)+ )++ entry = snaptrade_entry("buy_no_price")+ assert_not_nil entry, "a trade with units and amount but no price must still be imported"+ assert_equal BigDecimal("25"), entry.entryable.price+ assert_equal BigDecimal("4"), entry.entryable.qty+ assert_equal BigDecimal("100"), entry.amount++ log = snaptrade_debug_log("buy_no_price", level: "info")+ assert_equal "derived_price", log&.metadata&.dig("reason")+ assert_equal "25.0", log&.metadata&.dig("derived_price")+ end++ test "imports a fully reported trade without creating debug log" do+ process_activities(+ build_trade_activity(id: "buy_complete", type: "BUY", symbol: "AAPL", units: 3, price: 33.33, amount: -101.00, fee: 1.00)+ )++ assert_not_nil snaptrade_entry("buy_complete")+ assert DebugLogEntry.where(provider_key: "snaptrade").none? { |log| log.metadata["activity_id"] == "buy_complete" },+ "routine trades must not flood /settings/debug"+ end++ test "a price derived from amount and units excludes the fee for buys and sells" do+ process_activities(+ build_trade_activity(id: "buy_no_price_fee", type: "BUY", symbol: "AAPL", units: 10, price: nil, amount: -1505.00, fee: 5.00),+ build_trade_activity(id: "sell_no_price_fee", type: "SELL", symbol: "AAPL", units: 10, price: nil, amount: 1495.00, fee: 5.00)+ )++ assert_equal BigDecimal("150"), snaptrade_entry("buy_no_price_fee").entryable.price+ assert_equal BigDecimal("150"), snaptrade_entry("sell_no_price_fee").entryable.price+ end++ test "resyncing keeps the stored fee when SnapTrade omits it, but applies a reported zero" do+ process_activities(+ build_trade_activity(id: "buy_fee_omitted", type: "BUY", symbol: "AAPL", units: 10, price: 150.00, amount: -1504.95, fee: 4.95)+ )++ process_activities(+ build_trade_activity(id: "buy_fee_omitted", type: "BUY", symbol: "AAPL", units: 10, price: 150.00, amount: -1504.95)+ )+ assert_equal BigDecimal("4.95"), snaptrade_entry("buy_fee_omitted").entryable.reload.fee++ process_activities(+ build_trade_activity(id: "buy_fee_omitted", type: "BUY", symbol: "AAPL", units: 10, price: 150.00, amount: -1500.00, fee: 0)+ )+ assert_equal BigDecimal("0"), snaptrade_entry("buy_fee_omitted").entryable.reload.fee+ end++ test "resyncing corrects the amount of a previously imported trade" do+ process_activities(+ build_trade_activity(id: "buy_resync", type: "BUY", symbol: "AAPL", units: 3, price: 33.33)+ )+ assert_equal BigDecimal("99.99"), snaptrade_entry("buy_resync").amount++ assert_no_difference -> { @account.entries.count } do+ process_activities(+ build_trade_activity(id: "buy_resync", type: "BUY", symbol: "AAPL", units: 3, price: 33.33, amount: -100.00)+ )+ end++ assert_equal BigDecimal("100"), snaptrade_entry("buy_resync").amount+ end+test "processes dividend cash activity as negative inflow" do@snaptrade_account.update!(raw_activities_payload: [build_cash_activity(@@ -218,27 +343,84 @@ class SnaptradeAccount::ActivitiesProcessorTest < ActiveSupport::TestCaseendend- test "logs unmapped activity types" do- @snaptrade_account.update!(raw_activities_payload: [- build_cash_activity(- id: "unknown_001",- type: "SOME_NEW_TYPE",- amount: 100.00,- settlement_date: Date.current.to_s+ test "imports an unmapped activity type as Other and creates debug log" do+ process_activities(+ build_cash_activity(id: "unknown_001", type: "SOME_NEW_TYPE", amount: 100.00, settlement_date: Date.current.to_s)+ )++ entry = snaptrade_entry("unknown_001")+ assert_not_nil entry, "an unmapped activity type is still imported"+ assert_equal "Other", entry.entryable.investment_activity_label++ log = DebugLogEntry.where(provider_key: "snaptrade", category: "provider_sync", level: "warn")+ .find { |e| e.metadata["activity_type"] == "SOME_NEW_TYPE" }+ assert_not_nil log, "an unmapped activity type must be recorded in /settings/debug"+ assert_equal @family, log.family+ assert_equal @snaptrade_account.account_provider, log.account_provider+ end++ test "skips the trade and creates debug log when symbol is missing" do+ assert_no_difference -> { @account.entries.count } do+ process_activities(+ build_trade_activity(id: "skip_no_symbol", type: "BUY", symbol: nil, units: 1, price: 10.00, amount: -10.00))- ])+ end- # Capture log output- log_output = StringIO.new- old_logger = Rails.logger- Rails.logger = Logger.new(log_output)+ assert_equal "missing_symbol", snaptrade_debug_log("skip_no_symbol")&.metadata&.dig("reason")+ end- processor = SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account)- processor.process+ test "skips the trade and creates debug log when quantity is missing" do+ assert_no_difference -> { @account.entries.count } do+ process_activities(+ build_trade_activity(id: "skip_no_quantity", type: "BUY", symbol: "AAPL", units: nil, price: 10.00, amount: -10.00)+ )+ end- Rails.logger = old_logger+ assert_equal "missing_quantity", snaptrade_debug_log("skip_no_quantity")&.metadata&.dig("reason")+ end- assert_includes log_output.string, "Unmapped activity type 'SOME_NEW_TYPE'"+ test "skips the trade and creates debug log when amount and price are both missing" do+ assert_no_difference -> { @account.entries.count } do+ process_activities(+ build_trade_activity(id: "skip_no_amount", type: "BUY", symbol: "AAPL", units: 5, price: nil)+ )+ end++ log = snaptrade_debug_log("skip_no_amount")+ assert_equal "missing_amount", log&.metadata&.dig("reason")+ assert_equal @family, log.family+ assert_equal @snaptrade_account.account_provider, log.account_provider+ end++ test "skips the trade and creates debug log when security is unresolvable" do+ SnaptradeAccount::ActivitiesProcessor.any_instance.stubs(:resolve_security).returns(nil)++ assert_no_difference -> { @account.entries.count } do+ process_activities(+ build_trade_activity(id: "skip_unresolved", type: "BUY", symbol: "ZZZZ", units: 1, price: 10.00, amount: -10.00)+ )+ end++ log = snaptrade_debug_log("skip_unresolved")+ assert_equal "unresolved_security", log&.metadata&.dig("reason")+ assert_equal "ZZZZ", log&.metadata&.dig("ticker")+ end++ test "skips an activity that fails to import, keeps processing, and creates debug log" do+ Account::ProviderImportAdapter.any_instance.stubs(:import_trade).raises(StandardError, "boom")++ process_activities(+ build_trade_activity(id: "trade_fails", type: "BUY", symbol: "AAPL", units: 1, price: 10.00, amount: -10.00),+ build_cash_activity(id: "div_after_failure", type: "DIVIDEND", amount: 5.00, settlement_date: Date.current.to_s)+ )++ assert_nil snaptrade_entry("trade_fails")+ assert_not_nil snaptrade_entry("div_after_failure"), "later activities are still processed"++ log = snaptrade_debug_log("trade_fails", category: "provider_sync_error", level: "error")+ assert_not_nil log, "a failed activity must be recorded in /settings/debug"+ assert_equal "BUY", log.metadata["activity_type"]+ assert_includes log.message, "boom"endtest "skips activities without external_id" do@@ -283,8 +465,22 @@ class SnaptradeAccount::ActivitiesProcessorTest < ActiveSupport::TestCaseprivate- def build_trade_activity(id:, type:, symbol:, units:, price:, settlement_date:)- {+ def process_activities(*activities)+ @snaptrade_account.update!(raw_activities_payload: activities)+ SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account).process+ end++ def snaptrade_entry(external_id)+ @account.entries.find_by(external_id: external_id, source: "snaptrade")+ end++ def snaptrade_debug_log(activity_id, category: "provider_sync", level: "warn")+ DebugLogEntry.where(provider_key: "snaptrade", category: category, level: level)+ .find { |log| log.metadata["activity_id"] == activity_id }+ end++ def build_trade_activity(id:, type:, symbol:, units:, price:, settlement_date: Date.current.to_s, amount: nil, fee: nil)+ activity = {"id" => id,"type" => type,"symbol" => {@@ -296,6 +492,9 @@ class SnaptradeAccount::ActivitiesProcessorTest < ActiveSupport::TestCase"settlement_date" => settlement_date,"currency" => { "code" => "USD" }}+ activity["amount"] = amount unless amount.nil?+ activity["fee"] = fee unless fee.nil?+ activityenddef build_cash_activity(id:, type:, amount:, settlement_date:, symbol: nil)