The personal finance app for everyone (by everyone)
Ruby
Book Trade Republic trades on the linked cash account (#3770)
Niels Eulinkcd2b64b65430
diff --git a/app/models/trade_republic_account/activities_processor.rb b/app/models/trade_republic_account/activities_processor.rbindex aa4d29c038..48353541ce 100644--- a/app/models/trade_republic_account/activities_processor.rb+++ b/app/models/trade_republic_account/activities_processor.rb@@ -17,7 +17,7 @@ class TradeRepublicAccount::ActivitiesProcessortrade_count = 0transaction_count = 0- Array(@trade_republic_account.raw_timeline_payload).each do |event|+ timeline_events.each do |event|next unless event.is_a?(Hash)event = event.with_indifferent_access@@ -68,6 +68,29 @@ class TradeRepublicAccount::ActivitiesProcessor@trade_republic_account.currencyend+ # Trade Republic settles trades directly against the cash balance. The+ # importer keeps order executions on the portfolio payload only, so the+ # cash account reads them from there to book the settlement. Portfolio+ # copies come first so they win the dedupe: a cash snapshot retained from+ # a failed timeline update can still hold an order execution whose+ # portfolio copy has since been deleted.+ def timeline_events+ @timeline_events ||= begin+ events = Array(@trade_republic_account.raw_timeline_payload)+ events = portfolio_order_execution_events + events if @trade_republic_account.cash?+ events.uniq { |event| event.is_a?(Hash) ? (event["id"] || event[:id]).presence || event : event }+ end+ end++ def portfolio_order_execution_events+ portfolio = @trade_republic_account.trade_republic_item.trade_republic_accounts.find_by(kind: "portfolio")+ return [] unless portfolio++ Array(portfolio.raw_timeline_payload).select do |event|+ event.is_a?(Hash) && event_category(event.with_indifferent_access) == CATEGORY_ORDER_EXECUTION+ end+ end+# Saveback and Round Up stay classified as POC_CREATED at the client# boundary so other cash withdrawals are unchanged. Routing happens here# by eventType: Saveback is portfolio-only; Round Up is portfolio trade@@ -80,7 +103,6 @@ class TradeRepublicAccount::ActivitiesProcessorcategory = event[:category].to_sreturn category == CATEGORY_ORDER_EXECUTION if linked_cash_account_present? && @trade_republic_account.portfolio?- return category != CATEGORY_ORDER_EXECUTION if @trade_republic_account.cash?trueend@@ -107,10 +129,15 @@ class TradeRepublicAccount::ActivitiesProcessorcase event_category(event)when CATEGORY_ORDER_EXECUTIONreturn nil if duplicate_savings_plan_invoice?(event, detail, date)+ return import_order_settlement(event, detail, external_id, date) ? :transaction : nil if @trade_republic_account.cash?import_order_execution(event, detail, external_id, date) ? :trade : nilwhen CATEGORY_DEPOSIT- import_cash_movement(event, detail, external_id, date, label: cash_label(event, default: t("contribution")), sign: -1) ? :transaction : nil+ label = cash_label(event, default: nil)+ import_cash_movement(+ event, detail, external_id, date,+ label: label || t("contribution"), activity_label: label || deposit_activity_label, sign: -1+ ) ? :transaction : nilwhen CATEGORY_WITHDRAWALimport_cash_movement(event, detail, external_id, date, label: cash_label(event, default: t("withdrawal")), sign: 1) ? :transaction : nilwhen CATEGORY_INTEREST@@ -141,7 +168,10 @@ class TradeRepublicAccount::ActivitiesProcessorif @trade_republic_account.portfolio?import_order_execution(event, detail, external_id, date) ? :trade : nilelse- import_cash_movement(event, detail, external_id, date, label: t("round_up"), sign: 1) ? :transaction : nil+ import_cash_movement(+ event, detail, external_id, date,+ label: t("round_up"), sign: 1, kind: "investment_contribution"+ ) ? :transaction : nilendend@@ -168,7 +198,7 @@ class TradeRepublicAccount::ActivitiesProcessorenddef savings_plan_execution_keys- @savings_plan_execution_keys ||= Array(@trade_republic_account.raw_timeline_payload).each_with_object(Set.new) do |event, keys|+ @savings_plan_execution_keys ||= timeline_events.each_with_object(Set.new) do |event, keys|next unless event.is_a?(Hash)event = event.with_indifferent_access@@ -271,11 +301,40 @@ class TradeRepublicAccount::ActivitiesProcessortrueend- def import_cash_movement(event, detail, external_id, date, label:, sign:)+ # The timeline list amount is what Trade Republic booked against the cash+ # balance, fees and taxes included. Unlike cash movements (see+ # import_cash_movement), order executions carry a consistent sign across+ # topics: negative for buys, positive for sales. Payloads that only carry+ # a magnitude fall back to the traded quantity; without either signal the+ # direction is unknown and nothing is booked.+ # Buys count as investment contributions in budgets; sale proceeds are a+ # funds movement rather than income. Neither gets a category.+ def import_order_settlement(event, detail, external_id, date)+ signed_amount = parse_decimal(detail[:signed_amount])+ amount = signed_amount || parse_decimal(detail[:amount])+ return false unless amount && !amount.zero?++ quantity = parse_decimal(detail[:quantity])+ return false if signed_amount.nil? && (quantity.nil? || quantity.zero?)++ outflow = signed_amount ? signed_amount.negative? : quantity.positive?++ import_cash_movement(+ event,+ detail.merge(amount: amount.abs),+ external_id,+ date,+ label: outflow ? "Buy" : "Sell",+ sign: outflow ? 1 : -1,+ kind: outflow ? "investment_contribution" : "funds_movement"+ )+ end++ def import_cash_movement(event, detail, external_id, date, label:, sign:, activity_label: label, kind: nil)amount = parse_decimal(detail[:amount])return false unless amount && !amount.zero?- import_adapter.import_transaction(+ entry = import_adapter.import_transaction(external_id: external_id,# The normalized category is the source of truth for direction. TR# payloads use different signs across timeline topics, so forwarding@@ -288,8 +347,8 @@ class TradeRepublicAccount::ActivitiesProcessornotes: event[:subtitle].presence,source: "trade_republic",category_id: category_for(event, label)&.id,- kind: transfer_event?(event) ? "funds_movement" : nil,- investment_activity_label: label,+ kind: kind || (transfer_event?(event) ? "funds_movement" : nil),+ investment_activity_label: activity_label,extra: {trade_republic: {event_id: detail[:event_id] || external_id,@@ -303,10 +362,42 @@ class TradeRepublicAccount::ActivitiesProcessor}.compact})+ reset_legacy_contribution!(entry, event)trueend+ # The import adapter turns a Contribution label into investment_contribution,+ # a kind budgets count as an expense. On the cash account a deposit is money+ # arriving on a checking balance, so it carries no investment label.+ def deposit_activity_label+ @trade_republic_account.cash? ? nil : t("contribution")+ end++ # Earlier syncs stored cash-account deposits as investment contributions.+ # The adapter neither downgrades that kind nor clears the category and+ # label it assigned with it, so reset untouched inflows outside a matched+ # transfer.+ def reset_legacy_contribution!(entry, event)+ return unless @trade_republic_account.cash?++ transaction = entry&.entryable+ return unless transaction.is_a?(Transaction) && entry.amount.negative?+ return if entry.protected_from_sync? || transaction.transfer.present?++ attrs = {}+ attrs[:kind] = transfer_event?(event) ? "funds_movement" : "standard" if transaction.investment_contribution?+ attrs[:category_id] = nil if investment_contribution_category_ids.include?(transaction.category_id)+ attrs[:investment_activity_label] = nil if transaction.investment_activity_label == "Contribution"+ transaction.update!(attrs) if attrs.any?+ end++ def investment_contribution_category_ids+ @investment_contribution_category_ids ||= account.family.categories+ .where(name: Category.all_investment_contributions_names)+ .pluck(:id)+ end+def category_for(event, label)nilend@@ -493,7 +584,7 @@ class TradeRepublicAccount::ActivitiesProcessordef reconcile_non_importable_entries!explicit_ids = []heuristic_ids = []- Array(@trade_republic_account.raw_timeline_payload).each do |event|+ timeline_events.each do |event|next unless event.is_a?(Hash)next unless lifecycle_blocks_import?(event)diff --git a/app/models/trade_republic_account/data_helpers.rb b/app/models/trade_republic_account/data_helpers.rbindex 685ce76f9b..9bcd4e264f 100644--- a/app/models/trade_republic_account/data_helpers.rb+++ b/app/models/trade_republic_account/data_helpers.rb@@ -8,6 +8,7 @@ module TradeRepublicAccount::DataHelpersTRANSFER_EVENT_TYPES = %w[PAYMENT_INBOUND PAYMENT_OUTBOUND INCOMING_TRANSFER OUTGOING_TRANSFERINCOMING_TRANSFER_DELEGATION OUTGOING_TRANSFER_DELEGATION+ PAYMENT_INBOUND_SEPA_DIRECT_DEBIT PAYMENT_INBOUND_APPLE_PAY PAYMENT_INBOUND_GOOGLE_PAY].freezeclass << self@@ -312,18 +313,23 @@ module TradeRepublicAccount::DataHelpersreturn unless account.holdings.where(security_id: from_security.id).exists? ||account.trades.where(security_id: from_security.id).exists?- rematch_holdings_from_isin!(from_security, to_security)account.trades.where(security_id: from_security.id).update_all(security_id: to_security.id,updated_at: Time.current)+ rematch_holdings_from_isin!(from_security, to_security)end+ # Holdings are rewritten with update_columns: while trades are split across+ # the ISIN and exchange securities, calculated history can hold negative+ # quantities that fail validation, and the next materialization replaces+ # these rows anyway.def rematch_holdings_from_isin!(from_security, to_security)existing_keys = account.holdings.where(security_id: to_security.id).pluck(:date, :currency).to_set+ mismatched_dates = []account.holdings.where(security_id: from_security.id).find_each do |holding|key = [ holding.date, holding.currency ]@@ -344,38 +350,43 @@ module TradeRepublicAccount::DataHelpersattrs[:provider_security_id] = holding.provider_security_id.presence || from_security.idendattrs[:account_provider_id] = holding.account_provider_id if existing.account_provider_id.blank? && holding.account_provider_id.present?- attrs[:cost_basis] = holding.cost_basis if existing.cost_basis.blank? && holding.cost_basis.present?-- if existing.qty != holding.qty || existing.amount != holding.amount- DebugLogEntry.capture(- category: "sync",- level: "info",- message: "ISIN rematch collision kept exchange holding market values",- source: "trade_republic",- family: account.family,- provider_key: "trade_republic",- account: account,- metadata: {- from_security_id: from_security.id,- to_security_id: to_security.id,- date: holding.date,- isin_qty: holding.qty,- isin_amount: holding.amount,- exchange_qty: existing.qty,- exchange_amount: existing.amount- }- )+ if existing.cost_basis.blank? && holding.cost_basis.present?+ attrs[:cost_basis] = holding.cost_basis+ attrs[:cost_basis_source] = holding.cost_basis_source+ attrs[:cost_basis_locked] = holding.cost_basis_lockedend- existing.update!(attrs) if attrs.any?+ mismatched_dates << holding.date if existing.qty != holding.qty || existing.amount != holding.amount+holding.destroy!+ existing.update_columns(attrs.merge(updated_at: Time.current)) if attrs.any?else- holding.update!(+ holding.update_columns(security_id: to_security.id,- provider_security_id: holding.provider_security_id.presence || from_security.id+ provider_security_id: holding.provider_security_id.presence || from_security.id,+ updated_at: Time.current)existing_keys << keyendend++ return if mismatched_dates.empty?++ DebugLogEntry.capture(+ category: "sync",+ level: "info",+ message: "ISIN rematch collision kept exchange holding market values",+ source: "trade_republic",+ family: account.family,+ provider_key: "trade_republic",+ account: account,+ metadata: {+ from_security_id: from_security.id,+ to_security_id: to_security.id,+ collision_count: mismatched_dates.size,+ first_date: mismatched_dates.min,+ last_date: mismatched_dates.max+ }+ )endenddiff --git a/test/models/trade_republic_account_activities_processor_test.rb b/test/models/trade_republic_account_activities_processor_test.rbindex ada0025c5e..4df30dd523 100644--- a/test/models/trade_republic_account_activities_processor_test.rb+++ b/test/models/trade_republic_account_activities_processor_test.rb@@ -143,6 +143,26 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_includes rematched.name, "EXV1"end+ test "rematch moves ISIN trades even when split history left negative exchange holdings" do+ Security.stubs(:search_provider).returns([])+ event = order_execution_detail(event_id: "evt_split_history", quantity: "2", isin: "IE00B5BMR087", amount: "1024.92")++ import_event(event)+ isin_security = find_trade("trade_republic_event_evt_split_history").entryable.security+ exchange_security = Security.create!(ticker: "SXR8", exchange_operating_mic: "XETR", name: "Core S&P 500")+ date = Date.new(2024, 3, 28)+ @account.holdings.create!(security: isin_security, date: date, qty: 2, price: 511.96, amount: 1023.92, currency: "EUR")+ @account.holdings.create!(security: exchange_security, date: date, qty: 0, price: 511.96, amount: 0, currency: "EUR")+ .update_columns(qty: -0.5, amount: -255.98)++ import_event(event.deep_merge(detail: { symbol: "SXR8", exchange_slug: "XETR", name: "Core S&P 500" }))++ trade = find_trade("trade_republic_event_evt_split_history")+ assert_equal exchange_security.id, trade.entryable.security_id+ assert_includes trade.name, "SXR8"+ assert_not @account.holdings.where(security: isin_security).exists?+ end+test "sell imports negative quantity and positive amount" doimport_event(order_execution_detail(event_id: "evt_sell",@@ -525,6 +545,8 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_equal "Transaction", cash_entry.entryable_typeassert_equal BigDecimal("0.40"), cash_entry.amountassert_equal "Round up", cash_entry.transaction.investment_activity_label+ assert_equal "investment_contribution", cash_entry.transaction.kind+ assert_nil cash_entry.transaction.category_idassert_equal "SPARE_CHANGE_AGGREGATE", cash_entry.transaction.extra.dig("trade_republic", "event_type")end@@ -716,7 +738,119 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert entry.reload.user_modified?end- test "savings-plan invoice imports as a portfolio trade and never as cash" do+ test "split accounts settle buys and sells against the cash account" do+ cash_account, cash_sure = create_linked_cash_account!+ buy = order_execution_detail(event_id: "evt_settle_buy", quantity: "2.0", isin: "IE00B5BMR087", amount: "1024.92")+ .deep_merge(title: "Core S&P 500 USD (Acc)", subtitle: "Buy Order", detail: { signed_amount: -1024.92, fees: "1.0", price: "511.96" })+ sell = order_execution_detail(event_id: "evt_settle_sell", quantity: "-1.0", isin: "IE00B5BMR087", amount: "529.00")+ .deep_merge(title: "Core S&P 500 USD (Acc)", subtitle: "Sell Order", detail: { signed_amount: 529.0, fees: "1.0" })+ @tr_account.update!(raw_timeline_payload: [ buy, sell ])++ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_equal BigDecimal("-1024.92"), find_trade("trade_republic_event_evt_settle_buy").amount+ assert_equal 0, @account.entries.where(entryable_type: "Transaction").count++ buy_cash = cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_settle_buy")+ assert_equal BigDecimal("1024.92"), buy_cash.amount+ assert_equal "Core S&P 500 USD (Acc)", buy_cash.name+ assert_equal "Buy", buy_cash.transaction.investment_activity_label+ assert_equal "investment_contribution", buy_cash.transaction.kind+ assert_nil buy_cash.transaction.category_id++ sell_cash = cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_settle_sell")+ assert_equal BigDecimal("-529.0"), sell_cash.amount+ assert_equal "Sell", sell_cash.transaction.investment_activity_label+ assert_equal "funds_movement", sell_cash.transaction.kind+ assert_nil sell_cash.transaction.category_id++ assert_no_difference -> { cash_sure.entries.count } do+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ end+ end++ test "cash settlement is skipped when the trade direction is unknown" do+ cash_account, cash_sure = create_linked_cash_account!+ event = order_execution_detail(event_id: "evt_settle_unknown", quantity: nil, isin: "IE00B5BMR087", amount: "1024.92")+ @tr_account.update!(raw_timeline_payload: [ event ])++ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_not cash_sure.entries.exists?(external_id: "trade_republic_event_evt_settle_unknown")+ end++ test "cash settlement is removed when Trade Republic deletes the trade" do+ cash_account, cash_sure = create_linked_cash_account!+ buy = order_execution_detail(event_id: "evt_settle_deleted", quantity: "2.0", isin: "IE00B5BMR087", amount: "1024.92")+ @tr_account.update!(raw_timeline_payload: [ buy ])+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ assert cash_sure.entries.exists?(external_id: "trade_republic_event_evt_settle_deleted")++ @tr_account.update!(raw_timeline_payload: [ buy.merge(deleted: true) ])+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_not cash_sure.entries.exists?(external_id: "trade_republic_event_evt_settle_deleted")+ end++ test "a stale cash snapshot does not hide a trade deleted on the portfolio" do+ cash_account, cash_sure = create_linked_cash_account!+ buy = order_execution_detail(event_id: "evt_settle_stale", quantity: "2.0", isin: "IE00B5BMR087", amount: "1024.92")+ @tr_account.update!(raw_timeline_payload: [ buy ])+ cash_account.update!(raw_timeline_payload: [ buy ])+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ assert cash_sure.entries.exists?(external_id: "trade_republic_event_evt_settle_stale")++ @tr_account.update!(raw_timeline_payload: [ buy.merge(deleted: true) ])+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_not cash_sure.entries.exists?(external_id: "trade_republic_event_evt_settle_stale")+ end++ test "cash account deposits are fund movements, not investment contributions" do+ cash_account, cash_sure = create_linked_cash_account!+ wallet_top_up = deposit_event.merge(id: "evt_google_pay", eventType: "PAYMENT_INBOUND_GOOGLE_PAY", title: "Cash in")+ bank_credit = deposit_event.merge(id: "evt_bank_credit", eventType: "BANK_TRANSACTION_INCOMING", title: "Employer")+ cash_account.update!(raw_timeline_payload: [ wallet_top_up, bank_credit ])++ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ top_up = cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_google_pay").transaction+ assert_equal "funds_movement", top_up.kind+ assert_nil top_up.category_id++ credit = cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_bank_credit").transaction+ assert_equal "standard", credit.kind+ assert_nil credit.category_id+ end++ test "resets deposits that earlier syncs stored as investment contributions" do+ cash_account, cash_sure = create_linked_cash_account!+ category = @family.investment_contributions_category+ legacy = Account::ProviderImportAdapter.new(cash_sure).import_transaction(+ external_id: "trade_republic_event_evt_legacy_dep",+ amount: BigDecimal("-500.00"),+ currency: "EUR",+ date: Date.parse("2026-08-01"),+ name: "Cash in",+ source: "trade_republic",+ investment_activity_label: "Contribution"+ )+ assert_equal "investment_contribution", legacy.transaction.kind+ assert_equal category.id, legacy.transaction.category_id++ cash_account.update!(raw_timeline_payload: [+ deposit_event.merge(id: "evt_legacy_dep", eventType: "PAYMENT_INBOUND_GOOGLE_PAY", title: "Cash in")+ ])+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ legacy.transaction.reload+ assert_equal "funds_movement", legacy.transaction.kind+ assert_nil legacy.transaction.category_id+ assert_nil legacy.transaction.investment_activity_label+ end++ test "savings-plan invoice imports as a portfolio trade and a cash outflow" docash_account, cash_sure = create_linked_cash_account!event = savings_plan_invoice_event@@ -734,7 +868,9 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_equal BigDecimal("-25.00"), trade.amountassert_equal "SAVINGS_PLAN_INVOICE_CREATED", trade.entryable.extra.dig("trade_republic", "event_type")- assert_not Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_savings_plan")+ cash_entry = Entry.find_by!(account: cash_sure, external_id: "trade_republic_event_evt_savings_plan")+ assert_equal "Transaction", cash_entry.entryable_type+ assert_equal BigDecimal("25.00"), cash_entry.amountendtest "savings-plan invoice remains idempotent across repeated processing" do@@ -755,7 +891,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseendassert_equal 1, @account.entries.where(entryable_type: "Trade", source: "trade_republic").count- assert_equal 0, cash_sure.entries.where(source: "trade_republic").count+ assert_equal 1, cash_sure.entries.where(entryable_type: "Transaction", source: "trade_republic").countendtest "savings-plan invoice duplicated by an execution event imports once" do@@ -1005,7 +1141,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseendend- test "Google Pay inbound deposits import as contributions" do+ test "Google Pay inbound deposits import as fund movements" docash_account, cash_sure = create_linked_cash_account!cash_account.update!(raw_timeline_payload: [ {id: "evt_gpay",@@ -1019,7 +1155,8 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseentry = Entry.find_by!(account: cash_sure, external_id: "trade_republic_event_evt_gpay")assert_equal BigDecimal("-50.00"), entry.amount- assert_equal "Contribution", entry.transaction.investment_activity_label+ assert_equal "funds_movement", entry.transaction.kind+ assert_nil entry.transaction.investment_activity_labelendtest "Legal documents title without event type is ignored silently" dodiff --git a/test/models/trade_republic_account_holdings_processor_test.rb b/test/models/trade_republic_account_holdings_processor_test.rbindex a8628ea022..7169955887 100644--- a/test/models/trade_republic_account_holdings_processor_test.rb+++ b/test/models/trade_republic_account_holdings_processor_test.rb@@ -370,6 +370,8 @@ class TradeRepublicAccountHoldingsProcessorTest < ActiveSupport::TestCaseprice: 40,amount: 120,cost_basis: 38,+ cost_basis_source: "manual",+ cost_basis_locked: true,currency: "EUR",external_id: "stale-isin-holding",provider_security_id: prior_provider_security.id,@@ -400,6 +402,8 @@ class TradeRepublicAccountHoldingsProcessorTest < ActiveSupport::TestCaseassert_equal BigDecimal("5"), exchange_holding.qtyassert_equal BigDecimal("212.5"), exchange_holding.amountassert_equal BigDecimal("38"), exchange_holding.cost_basis+ assert_equal "manual", exchange_holding.cost_basis_source+ assert exchange_holding.cost_basis_lockedassert_equal prior_provider_security.id, exchange_holding.provider_security_idend