The personal finance app for everyone (by everyone)
Ruby
fix(trade-republic): resolve bonds by ISIN and import bond purchases (#4060)
Niels Eulinkde54bf5b0d11
diff --git a/app/models/provider/trade_republic_client.rb b/app/models/provider/trade_republic_client.rbindex d69559aad1..4e8f714195 100644--- a/app/models/provider/trade_republic_client.rb+++ b/app/models/provider/trade_republic_client.rb@@ -83,7 +83,12 @@ class Provider::TradeRepublicClient# that merely echo the ISIN (common on TIB).INSTRUMENT_EXCHANGE_PREFERENCE = %w[XETR TDG].freezeINSTRUMENT_EXCHANGE_LAST_RESORT = %w[LSX].freeze- INSTRUMENT_SYMBOL_CATEGORIES = %w[stocksAndETFs bonds].freeze+ # Bonds are left out: Trade Republic lists every bond on LSX under the same+ # placeholder symbol "BOND", so they resolve by ISIN instead.+ INSTRUMENT_SYMBOL_CATEGORIES = %w[stocksAndETFs].freeze+ BOND_INSTRUMENT_TYPE = "bond"+ BOND_PLACEHOLDER_SYMBOL = "BOND"+ BOND_PLACEHOLDER_EXCHANGE = "LSX"FEE_TITLES = ["gebühr", "fee", "fees", "kosten", "costs", "cost", "commission", "kommission"].freeze@@ -98,6 +103,11 @@ class Provider::TradeRepublicClient"share price", "aandelenkoers", "aktienkurs", "anteilskurs","execution price", "kurs"].freeze+ # Bond executions list a nominal amount and a price in percent of par+ # instead of shares and a share price.+ NOMINAL_TITLES = [ "nennwert", "face value" ].freeze+ QUOTATION_TITLES = [ "quotation" ].freeze+ BOND_TOTAL_TITLES = [ "summe", "total" ].freezeSELL_SUBTITLE_MARKERS = %w[sell verkauf verkaufen verkopen].freezeMAX_TIMELINE_PAGES = 50TIMELINE_TOPICS = %w[timelineTransactions timelineActivityLog].freeze@@ -124,8 +134,12 @@ class Provider::TradeRepublicClientPRICE_BACKFILL_ATTEMPTED_AT_KEY = "price_backfill_attempted_at"SYMBOL_LOOKUP_ATTEMPTED_AT_KEY = "symbol_lookup_attempted_at"SYMBOL_LOOKUP_FIRST_ATTEMPTED_AT_KEY = "symbol_lookup_first_attempted_at"+ # Stored trades whose detail is still incomplete after a fetch; the backlog+ # retries the least recently attempted first.+ DETAIL_BACKFILL_ATTEMPTED_AT_KEY = "detail_backfill_attempted_at"RETRY_MARKER_KEYS = [- PRICE_BACKFILL_ATTEMPTED_AT_KEY, SYMBOL_LOOKUP_ATTEMPTED_AT_KEY, SYMBOL_LOOKUP_FIRST_ATTEMPTED_AT_KEY+ PRICE_BACKFILL_ATTEMPTED_AT_KEY, SYMBOL_LOOKUP_ATTEMPTED_AT_KEY, SYMBOL_LOOKUP_FIRST_ATTEMPTED_AT_KEY,+ DETAIL_BACKFILL_ATTEMPTED_AT_KEY].freeze# Cap instrument lookups for sold / historical trade ISINs that are absent# from the current portfolio snapshot.@@ -543,6 +557,16 @@ class Provider::TradeRepublicClientattempted_at <= now - RETRY_INTERVALend+ # Backlog order for stored events needing details: never-attempted events+ # first, oldest first, then the least recently attempted, so events that+ # stay incomplete can't hold the budget on every sync. Price backfills+ # carry no detail attempt; trade_detail_needs_price_backfill? paces them.+ def detail_backfill_sort_key(event)+ return [ 0, "" ] unless event.is_a?(Hash)++ [ detail_time(event, DETAIL_BACKFILL_ATTEMPTED_AT_KEY).to_i, (event["timestamp"] || event[:timestamp]).to_s ]+ end+# Stored trades whose ISIN found no usable exchange symbol are retried at# most once per RETRY_INTERVAL, for RETRY_WINDOW after the first attempt.def symbol_lookup_due?(event, now = Time.current)@@ -564,6 +588,35 @@ class Provider::TradeRepublicClientdetail["price"].to_s.strip.blank?end+ # Earlier syncs stored this listing on bond positions and trades.+ def bond_placeholder_listing?(symbol, exchange_slug)+ symbol.to_s.strip.casecmp?(BOND_PLACEHOLDER_SYMBOL) &&+ exchange_slug.to_s.strip.casecmp?(BOND_PLACEHOLDER_EXCHANGE)+ end++ def bond?(detail)+ detail.is_a?(Hash) && detail.with_indifferent_access[:instrument_type].to_s == BOND_INSTRUMENT_TYPE+ end++ # The ISIN of a stored or new trade that still needs an exchange ticker,+ # or nil. Bonds never get one.+ def symbol_lookup_isin(event)+ return nil unless event.is_a?(Hash)+ return nil unless requires_trade_detail?(event)+ return nil unless Provider::TradeRepublicTimelineEvent.importable?(event)++ detail = event["detail"] || event[:detail]+ return nil unless detail.is_a?(Hash)++ detail = detail.stringify_keys+ isin = detail["isin"].to_s.presence+ return nil if isin.blank? || bond?(detail)++ symbol = detail["symbol"].to_s.strip.presence+ usable = symbol.present? && !symbol.casecmp?(isin) && detail["exchange_slug"].to_s.strip.present?+ isin unless usable+ end+def instrument_symbols_from_positions(positions)Array(positions).each_with_object({}) do |position, map|next unless position.is_a?(Hash)@@ -859,6 +912,11 @@ class Provider::TradeRepublicClientvalid_positions.each do |position|isin = position["instrumentId"].presence || position["isin"]next if instruments.key?(isin)++ if position["categoryType"].to_s == "bonds"+ instruments[isin] = bond_instrument(websocket, isin)+ next+ endnext unless INSTRUMENT_SYMBOL_CATEGORIES.include?(position["categoryType"].to_s)known = known_symbols[isin]@@ -875,8 +933,9 @@ class Provider::TradeRepublicClientinstrument = instruments[isin] || {}{"isin" => isin,- "name" => position["name"],+ "name" => instrument[:name].presence || position["name"],"category" => portfolio_category(position["categoryType"]),+ "instrument_type" => instrument[:instrument_type],"quantity" => decimal_string(quantity),"average_cost" => decimal_string(position["averageBuyIn"] || position["avgCost"]),"price" => prices[isin],@@ -999,10 +1058,46 @@ class Provider::TradeRepublicClient# Returns { symbol:, exchange_slug: } from the instrument subscription, or# nil when Trade Republic has no usable exchange ticker for this ISIN.def instrument_exchange_symbol(websocket, isin)- payload = optional_subscribe(websocket, type: "instrument", id: isin)+ payload = instrument_payload(websocket, isin)+ pick_instrument_exchange_symbol(payload, isin) if payload+ end++ # The portfolio names a bond by its localized maturity ("März 2040"); the+ # instrument name also carries the issuer ("ITALIEN 19/40").+ def bond_instrument(websocket, isin)+ { name: instrument_name(websocket, isin), instrument_type: BOND_INSTRUMENT_TYPE }.compact+ end++ def instrument_name(websocket, isin)+ bond_name(instrument_payload(websocket, isin))+ end++ # Bonds are named like the market lists them: issuer, coupon and maturity+ # ("Italy 3.1% Mar 2040"). The instrument name is the exchange's German+ # name ("ITALIEN 19/40") even with locale "en", so it is only the fallback.+ def bond_name(payload)return nil unless payload.is_a?(Hash)- pick_instrument_exchange_symbol(payload, isin)+ bond_info = payload["bondInfo"].is_a?(Hash) ? payload["bondInfo"] : {}+ issuer = bond_info["issuerName"].to_s.strip.presence+ maturity = payload["shortName"].to_s.strip.presence+ return payload["name"].to_s.strip.presence unless issuer && maturity++ [ issuer, bond_coupon(bond_info), maturity ].compact.join(" ")+ end++ # A fixed coupon never changes, so it can go in a name that is only set+ # when the security is created. Floating rates are left out.+ def bond_coupon(bond_info)+ return nil unless bond_info["interestRateType"] == "FIXED_INTEREST_RATE"++ rate = finite_decimal(bond_info["interestRate"])+ "#{(rate * 100).round(4).to_s("F").delete_suffix(".0")}%" if rate+ end++ def instrument_payload(websocket, isin)+ payload = optional_subscribe(websocket, type: "instrument", id: isin)+ payload if payload.is_a?(Hash)rescue TransientProviderError, RateLimitedraiserescue Error@@ -1039,28 +1134,44 @@ class Provider::TradeRepublicClientendstamp_instrument_symbols_on_events!(events, symbols)+ stamp_bond_instrument_names!(websocket, events, budget: MAX_INSTRUMENT_LOOKUPS - looked_up)symbolsend- def trade_isins_missing_symbols(events, known_symbols)- missing = []+ # A sold bond has no position to name its ISIN security after, and its+ # timeline title only names the maturity ("März 2040"). Stamp the+ # instrument name on bond trades while they pass through a sync, so the+ # security is created with it.+ def stamp_bond_instrument_names!(websocket, events, budget:)+ names = {}Array(events).each do |event|next unless event.is_a?(Hash)- next unless self.class.requires_trade_detail?(event)- next unless Provider::TradeRepublicTimelineEvent.importable?(event)detail = event["detail"] || event[:detail]- next unless detail.is_a?(Hash)+ next unless self.class.bond?(detail)detail = detail.stringify_keysisin = detail["isin"].to_s.presence- next if isin.blank?- next if known_symbols.key?(isin)- next if usable_trade_symbol?(detail["symbol"], isin) && detail["exchange_slug"].to_s.strip.present?+ next if isin.blank? || detail["instrument_name"].present?++ unless names.key?(isin)+ next if names.size >= budget- missing << isin+ names[isin] = instrument_name(websocket, isin)+ end+ next if names[isin].blank?++ detail["instrument_name"] = names[isin]+ event["detail"] = detailend- missing.uniq+ events+ end++ def trade_isins_missing_symbols(events, known_symbols)+ Array(events).filter_map do |event|+ isin = self.class.symbol_lookup_isin(event)+ isin unless isin.nil? || known_symbols.key?(isin)+ end.uniqenddef stamp_instrument_symbols_on_events!(events, symbols)@@ -1111,6 +1222,8 @@ class Provider::TradeRepublicClientenddef pick_instrument_exchange_symbol(payload, isin)+ return nil if payload["typeId"].to_s == BOND_INSTRUMENT_TYPE+candidates = Array(payload["exchanges"]).filter_map do |exchange|next unless exchange.is_a?(Hash)next if exchange.key?("active") && !ActiveModel::Type::Boolean.new.cast(exchange["active"])@@ -1468,7 +1581,11 @@ class Provider::TradeRepublicClientif kind == :backfillresult = fetched ? prefer_richer_event(item, fetched) : itemdetail_backfill_count += 1 if detail_backfill_improved?(item, result)- fetched = with_price_backfill_attempt(result) if self.class.trade_detail_missing_price?(result)+ if self.class.trade_detail_missing_price?(result)+ fetched = with_price_backfill_attempt(result)+ elsif self.class.incomplete_trade_detail_event?(result) || self.class.dividend_detail_missing?(result)+ fetched = with_detail_backfill_attempt(result)+ endendenriched_by_id[item["id"].to_s] = fetched if fetchedend@@ -1490,10 +1607,14 @@ class Provider::TradeRepublicClientself.class.trade_detail_missing_price?(before) && !self.class.trade_detail_missing_price?(after)end- def with_price_backfill_attempt(event)+ def with_price_backfill_attempt(event) = with_attempt_marker(event, PRICE_BACKFILL_ATTEMPTED_AT_KEY)++ def with_detail_backfill_attempt(event) = with_attempt_marker(event, DETAIL_BACKFILL_ATTEMPTED_AT_KEY)++ def with_attempt_marker(event, key)event = event.stringify_keysdetail = (event["detail"] || {}).stringify_keys- event.merge("detail" => detail.merge(PRICE_BACKFILL_ATTEMPTED_AT_KEY => Time.current.iso8601))+ event.merge("detail" => detail.merge(key => Time.current.iso8601))end# Test/helper wrapper: enrich a raw timeline page without touching the list cursor.@@ -1561,13 +1682,19 @@ class Provider::TradeRepublicClientenddef normalize_event_detail(raw, item: nil)- rows = collect_sections(raw).flat_map { |section| Array(section["data"]) }.select { |row| row.is_a?(Hash) }+ rows = section_rows(collect_sections(raw))shares = find_row(rows, SHARE_TITLES)total = find_row(rows, TOTAL_TITLES)price_row = find_row(rows, PRICE_TITLES)fees = find_row(rows, FEE_TITLES)taxes = find_row(rows, TAX_TITLES)- quantity = decimal_from_row(shares) || quantity_from_raw(raw)+ # A bond's nominal and quote sit in an untitled table inside an infoPage+ # bottom sheet. Only bond fields read it, so an unrelated nested table+ # can't fill in a share trade's price or total.+ bond_rows = rows + section_rows(collect_sections(raw, untitled_tables: true)) unless shares+ nominal = find_row(bond_rows, NOMINAL_TITLES) unless shares+ total ||= find_row(bond_rows, BOND_TOTAL_TITLES) if nominal+ quantity = decimal_from_row(shares) || decimal_from_row(nominal) || quantity_from_raw(raw)title = shares&.dig("title").to_s.downcasequantity = -quantity.abs if title.include?("entfernt") || title.include?("removed") || title.include?("gesendet") || title.include?("sent")subtitle = item&.dig("subtitle").to_s.downcase@@ -1576,6 +1703,10 @@ class Provider::TradeRepublicClientfee_amount = decimal_from_row(fees)tax_amount = decimal_from_row(taxes)price = decimal_from_row(price_row)+ quotation = decimal_from_row(find_row(bond_rows, QUOTATION_TITLES)) if nominal+ # Per unit of nominal, like a bond position's averageBuyIn: 92,67 % of+ # par is 0.9267.+ price ||= quotation / 100 if quotationdividend_per_share = decimal_from_row(find_row(rows, DIVIDEND_PER_SHARE_TITLES))if price.nil? && quantity&.nonzero? && amount# Provider cash totals embed costs: buy total = gross + fees/taxes,@@ -1596,20 +1727,24 @@ class Provider::TradeRepublicClient"currency" => currency_from_row(total) || currency_from_row(shares) || currency_from_row(price_row),"fees" => decimal_string(fee_amount),"taxes" => decimal_string(tax_amount),- "dividend_per_share" => decimal_string(dividend_per_share)+ "dividend_per_share" => decimal_string(dividend_per_share),+ "instrument_type" => (BOND_INSTRUMENT_TYPE if nominal)}.compactend- def collect_sections(node, result = [])+ def collect_sections(node, result = [], untitled_tables: false)case nodewhen Hash- result << node if node.key?("title") && node["data"].is_a?(Array)- node.each_value { |value| collect_sections(value, result) }- when Array then node.each { |value| collect_sections(value, result) }+ section = untitled_tables ? node["type"] == "table" && !node.key?("title") : node.key?("title")+ result << node if section && node["data"].is_a?(Array)+ node.each_value { |value| collect_sections(value, result, untitled_tables:) }+ when Array then node.each { |value| collect_sections(value, result, untitled_tables:) }endresultend+ def section_rows(sections) = sections.flat_map { |section| Array(section["data"]) }.select { |row| row.is_a?(Hash) }+def find_row(rows, titles) = rows.find { |row| titles.include?(row["title"].to_s.downcase.strip) }def decimal_from_row(row)diff --git a/app/models/trade_republic_account/activities_processor.rb b/app/models/trade_republic_account/activities_processor.rbindex 1ddb215f6b..889bf3d6c6 100644--- a/app/models/trade_republic_account/activities_processor.rb+++ b/app/models/trade_republic_account/activities_processor.rb@@ -295,7 +295,7 @@ class TradeRepublicAccount::ActivitiesProcessorsecurity = resolve_security(isin,- detail[:name] || event[:title],+ detail[:instrument_name] || detail[:name] || event[:title],symbol: detail[:symbol],exchange_slug: detail[:exchange_slug])@@ -345,7 +345,9 @@ class TradeRepublicAccount::ActivitiesProcessorfee: fee,currency: detail[:currency].presence || currency,date: date,- name: build_trade_name(detail[:name], security, signed_quantity),+ # A bond's timeline title is only its maturity ("März 2040"); the+ # security carries the instrument name the holding shows.+ name: build_trade_name(Provider::TradeRepublicClient.bond?(detail) ? nil : detail[:name], security, signed_quantity),source: "trade_republic",activity_label: is_buy ? "Buy" : "Sell")diff --git a/app/models/trade_republic_account/data_helpers.rb b/app/models/trade_republic_account/data_helpers.rbindex dedf54d84a..05882db1a7 100644--- a/app/models/trade_republic_account/data_helpers.rb+++ b/app/models/trade_republic_account/data_helpers.rb@@ -148,6 +148,8 @@ module TradeRepublicAccount::DataHelpersposition = position_metadata_for(isin)symbol = symbol.to_s.presence || position&.dig(:symbol)exchange_slug = exchange_slug.to_s.presence || position&.dig(:exchange_slug)+ return nil if Provider::TradeRepublicClient.bond_placeholder_listing?(symbol, exchange_slug)+mic = mic_for_exchange_slug(exchange_slug)usable_symbol = usable_exchange_symbol(symbol, isin)@@ -351,18 +353,34 @@ module TradeRepublicAccount::DataHelpersrematch_holdings_from_isin!(from_security, to_security)end+ def rematch_holdings_from_isin!(from_security, to_security)+ mismatched_dates = move_holdings_to_security!(account.holdings.where(security_id: from_security.id), to_security)+ log_rematch_collisions(+ "ISIN rematch collision kept exchange holding market values",+ mismatched_dates,+ from_security_id: from_security.id,+ to_security_id: to_security.id+ )+ 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)+ #+ # `provider_security_id` normally keeps the security the provider first+ # reported, so a user can reset a remapped holding. `adopt_provider_security`+ # replaces it when that original security was itself wrong.+ #+ # Returns the dates where both rows existed with different values.+ def move_holdings_to_security!(holdings, to_security, adopt_provider_security: false)existing_keys = account.holdings.where(security_id: to_security.id).pluck(:date, :currency).to_setmismatched_dates = []- account.holdings.where(security_id: from_security.id).find_each do |holding|+ holdings.find_each do |holding|key = [ holding.date, holding.currency ]if existing_keys.include?(key)existing = account.holdings.find_by!(@@ -370,15 +388,15 @@ module TradeRepublicAccount::DataHelpersdate: holding.date,currency: holding.currency)- # Both rows are the same position after ISIN→ticker rematch (live- # exchange holding from HoldingsProcessor vs stale ISIN row). Keep- # exchange market qty/amount/price — summing would double-count.- # Merge provider tracking and cost basis from the ISIN row when the- # exchange row is missing them.+ # Both rows are the same position after the rematch (live holding+ # from HoldingsProcessor vs stale row). Keep the live market+ # qty/amount/price — summing would double-count. Merge provider+ # tracking and cost basis from the stale row when the live row is+ # missing them.attrs = {}attrs[:external_id] = holding.external_id if existing.external_id.blank? && holding.external_id.present?- if existing.provider_security_id.blank?- attrs[:provider_security_id] = holding.provider_security_id.presence || from_security.id+ if existing.provider_security_id.blank? && !adopt_provider_security+ attrs[:provider_security_id] = holding.provider_security_id.presence || holding.security_idendattrs[:account_provider_id] = holding.account_provider_id if existing.account_provider_id.blank? && holding.account_provider_id.present?if existing.cost_basis.blank? && holding.cost_basis.present?@@ -392,32 +410,35 @@ module TradeRepublicAccount::DataHelpersholding.destroy!existing.update_columns(attrs.merge(updated_at: Time.current)) if attrs.any?else+ provider_security_id = adopt_provider_security ? to_security.id : holding.provider_security_id.presence || holding.security_idholding.update_columns(security_id: to_security.id,- provider_security_id: holding.provider_security_id.presence || from_security.id,+ provider_security_id: provider_security_id,updated_at: Time.current)existing_keys << keyendend+ mismatched_dates+ end++ def log_rematch_collisions(message, mismatched_dates, **metadata)return if mismatched_dates.empty?DebugLogEntry.capture(category: "sync",level: "info",- message: "ISIN rematch collision kept exchange holding market values",+ message: message,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,+ metadata: metadata.merge(collision_count: mismatched_dates.size,first_date: mismatched_dates.min,last_date: mismatched_dates.max- }+ ))endenddiff --git a/app/models/trade_republic_account/holdings_processor.rb b/app/models/trade_republic_account/holdings_processor.rbindex cf8d9a3d5d..136ec91cbf 100644--- a/app/models/trade_republic_account/holdings_processor.rb+++ b/app/models/trade_republic_account/holdings_processor.rb@@ -20,6 +20,8 @@ class TradeRepublicAccount::HoldingsProcessorif @trade_republic_account.positions_snapshot_complete? && processed_count == positions.sizereconcile_stale_holdings!(positions)end++ purge_shared_bond_calculated_holdings!endprivate@@ -48,6 +50,8 @@ class TradeRepublicAccount::HoldingsProcessor)return unless security+ rematch_bond_holdings!(isin, security) if bond_position?(position)+quantity = parse_decimal(position[:quantity])price = parse_decimal(position[:price])return unless quantity && price && quantity.positive?@@ -55,7 +59,7 @@ class TradeRepublicAccount::HoldingsProcessoramount = quantity * pricedate = Date.current- external_id = "trade_republic_position_#{@trade_republic_account.trade_republic_account_id}_#{isin}_#{date}"+ external_id = "#{position_external_id_prefix}#{isin}_#{date}"import_adapter.import_holding(security: security,@@ -84,11 +88,77 @@ class TradeRepublicAccount::HoldingsProcessorfalseend+ # Positions stored before bonds were marked still carry the shared+ # listing; they are bonds as well.+ def bond_position?(position)+ Provider::TradeRepublicClient.bond?(position) ||+ Provider::TradeRepublicClient.bond_placeholder_listing?(position[:symbol], position[:exchange_slug])+ end++ # Earlier syncs put every bond on Trade Republic's shared "BOND" listing.+ # The external id still names the bond's ISIN, so move this bond's+ # snapshots onto its own security. The shared listing was never the+ # bond's real security, so it doesn't stay as provider_security_id, also+ # not on rows that import_holding already moved.+ def rematch_bond_holdings!(isin, security)+ bond_holdings = account.holdings+ .where("external_id LIKE ?", "#{ActiveRecord::Base.sanitize_sql_like("#{position_external_id_prefix}#{isin}_")}%")+ stale = bond_holdings.where.not(security_id: security.id).where(security_locked: false)++ if stale.exists?+ mismatched_dates = move_holdings_to_security!(stale, security, adopt_provider_security: true)+ log_rematch_collisions(+ "Bond rematch collision kept the bond's own holding market values",+ mismatched_dates,+ isin: isin,+ to_security_id: security.id+ )+ end++ bond_holdings+ .where(security_id: security.id, security_locked: false)+ .where.not(provider_security_id: [ nil, security.id ])+ .update_all(provider_security_id: security.id, updated_at: Time.current)+ end++ # Earlier syncs calculated daily holdings on the shared BOND listing.+ # Reverse syncs never purge calculated rows, and bond history is now+ # calculated on each bond's own security, so leaving them counts bonds+ # twice. Rows still backed by trades on the listing are recalculated.+ def purge_shared_bond_calculated_holdings!+ removed_count = account.holdings+ .where(security_id: shared_bond_security_ids, account_provider_id: nil, security_locked: false)+ .delete_all+ return unless removed_count.positive?++ DebugLogEntry.capture(+ category: "sync",+ level: "info",+ message: "Removed #{removed_count} holding(s) calculated on the shared Trade Republic BOND listing",+ source: "trade_republic",+ family: account.family,+ provider_key: "trade_republic",+ account: account,+ metadata: { trade_republic_account_id: @trade_republic_account.id, removed_count: removed_count }+ )+ end++ def shared_bond_security_ids+ Security.where(+ ticker: Provider::TradeRepublicClient::BOND_PLACEHOLDER_SYMBOL,+ exchange_operating_mic: EXCHANGE_SLUG_TO_MIC[Provider::TradeRepublicClient::BOND_PLACEHOLDER_EXCHANGE]+ ).select(:id)+ end++ def position_external_id_prefix+ "trade_republic_position_#{@trade_republic_account.trade_republic_account_id}_"+ end+def reconcile_stale_holdings!(positions)provider_id = @trade_republic_account.account_provider&.idreturn if provider_id.blank?- prefix = "trade_republic_position_#{@trade_republic_account.trade_republic_account_id}_"+ prefix = position_external_id_prefixcurrent_ids = positions.filter_map do |position|isin = position.with_indifferent_access[:isin].to_sisin.present? ? "#{prefix}#{isin}_#{Date.current}" : nildiff --git a/app/models/trade_republic_item/importer.rb b/app/models/trade_republic_item/importer.rbindex 6bef6a3a0b..c253117e0d 100644--- a/app/models/trade_republic_item/importer.rb+++ b/app/models/trade_republic_item/importer.rb@@ -238,8 +238,7 @@ class TradeRepublicItem::Importer# Incomplete trade-detail events, complete trades still missing a share# price (stored before execution price/fees were parsed) and dividends- # without their detail. Oldest first so repeated syncs progressively drain- # historical starvation.+ # without their detail, in the client's backlog order.def events_needing_detail_enrichmentportfolio = trade_republic_item.trade_republic_accounts.find_by(kind: "portfolio")return [] unless portfolio@@ -250,7 +249,7 @@ class TradeRepublicItem::ImporterProvider::TradeRepublicClient.trade_detail_needs_price_backfill?(event) ||Provider::TradeRepublicClient.dividend_detail_missing?(event)end- .sort_by { |event| event_timestamp(event) }+ .sort_by { |event| Provider::TradeRepublicClient.detail_backfill_sort_key(event) }.first(Provider::TradeRepublicClient::MAX_TIMELINE_DETAILS)end@@ -262,24 +261,8 @@ class TradeRepublicItem::Importerreturn [] unless portfolioArray(portfolio.raw_timeline_payload).filter_map do |event|- next unless event.is_a?(Hash)- next unless Provider::TradeRepublicClient.requires_trade_detail?(event)- next unless Provider::TradeRepublicTimelineEvent.importable?(event)-- detail = (event["detail"] || event[:detail])- next unless detail.is_a?(Hash)-- detail = detail.stringify_keys- isin = detail["isin"].to_s.presence- next if isin.blank?-- symbol = detail["symbol"].to_s.strip.presence- exchange_slug = detail["exchange_slug"].to_s.strip.presence- usable = symbol.present? && !symbol.casecmp?(isin) && exchange_slug.present?- next if usable- next unless Provider::TradeRepublicClient.symbol_lookup_due?(event)-- isin+ isin = Provider::TradeRepublicClient.symbol_lookup_isin(event)+ isin if isin && Provider::TradeRepublicClient.symbol_lookup_due?(event)end.uniq.first(Provider::TradeRepublicClient::MAX_INSTRUMENT_LOOKUPS)end@@ -292,12 +275,6 @@ class TradeRepublicItem::ImporterProvider::TradeRepublicClient.instrument_symbols_from_positions(portfolio.raw_positions_payload)end- def event_timestamp(event)- return "" unless event.is_a?(Hash)-- (event["timestamp"] || event[:timestamp]).to_s- end-# Advance the list cursor whenever timeline pagination finished, even when# a detail backlog remains for later syncs. The per-topic newest events in# timeline_cursors take precedence; this column seeds topics withoutdiff --git a/test/models/trade_republic_account_activities_processor_test.rb b/test/models/trade_republic_account_activities_processor_test.rbindex beb96bafe7..74784a6c5d 100644--- a/test/models/trade_republic_account_activities_processor_test.rb+++ b/test/models/trade_republic_account_activities_processor_test.rb@@ -1792,17 +1792,19 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseendend- test "price backfill attempt marker stays out of the transaction provider detail" do+ test "retry attempt markers stay out of the transaction provider detail" do+ markers = Provider::TradeRepublicClient::RETRY_MARKER_KEYS+ assert_includes markers, Provider::TradeRepublicClient::DETAIL_BACKFILL_ATTEMPTED_AT_KEYcash_account, cash_sure = create_linked_cash_account!cash_account.update!(raw_timeline_payload: [ deposit_event.deep_merge(- detail: { Provider::TradeRepublicClient::PRICE_BACKFILL_ATTEMPTED_AT_KEY => "2026-08-01T10:00:00Z" }+ detail: markers.index_with { "2026-08-01T10:00:00Z" }) ])TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).processentry = Entry.find_by!(account: cash_sure, external_id: "trade_republic_event_evt_dep")provider_detail = entry.entryable.extra.dig("trade_republic", "provider_detail")- assert_not provider_detail.key?(Provider::TradeRepublicClient::PRICE_BACKFILL_ATTEMPTED_AT_KEY)+ assert_empty provider_detail.keys & markersendtest "preserves protected entries when reconciling declined upstream events" do@@ -1834,6 +1836,94 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert entry.reload.user_modified?end+ test "bond purchase books nominal and percent-of-par price on the bond's own security" do+ @tr_account.update!(raw_positions_payload: [+ {+ "isin" => "IT0005377152",+ "name" => "ITALIEN 19/40",+ "category" => "interest_products",+ "instrument_type" => "bond",+ "quantity" => "2677.95",+ "price" => "0.8404"+ }+ ])+ TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload).process++ import_event({+ id: "evt_bond",+ timestamp: "2025-11-18T11:19:31Z",+ category: "orderExecution",+ title: "März 2040",+ detail: {+ isin: "IT0005377152",+ name: "März 2040",+ quantity: "2677.95",+ price: "0.9267",+ amount: "2498.31",+ fees: "1.0",+ currency: "EUR",+ instrument_type: "bond"+ }+ })++ entry = find_trade("trade_republic_event_evt_bond")+ trade = entry.entryable+ assert_equal "IT0005377152", trade.security.ticker+ assert trade.security.offline?+ assert_equal @account.holdings.first.security, trade.security+ assert_equal BigDecimal("2677.95"), trade.qty+ assert_equal BigDecimal("0.9267"), trade.price+ assert_equal BigDecimal("1"), trade.fee+ assert_equal BigDecimal("2498.31"), entry.amount+ assert_equal "IT0005377152 · 2677.95x ITALIEN 19/40", entry.name+ end++ test "a sold bond's security takes the instrument name stamped on its trade" do+ import_event({+ id: "evt_sold_bond",+ timestamp: "2025-11-18T11:19:31Z",+ category: "orderExecution",+ title: "März 2040",+ detail: {+ isin: "IT0005377152",+ name: "März 2040",+ instrument_name: "ITALIEN 19/40",+ quantity: "-2677.95",+ price: "0.95",+ amount: "2544.05",+ currency: "EUR",+ instrument_type: "bond"+ }+ })++ entry = find_trade("trade_republic_event_evt_sold_bond")+ assert_equal "ITALIEN 19/40", entry.entryable.security.name+ assert_equal "IT0005377152 · 2677.95x ITALIEN 19/40", entry.name+ end++ test "stored bond trades on the legacy BOND listing resolve by ISIN" do+ Security.expects(:search_provider).never+ import_event({+ id: "evt_legacy_bond",+ timestamp: "2025-11-18T11:19:31Z",+ category: "orderExecution",+ detail: {+ isin: "IT0005377152",+ name: "März 2040",+ quantity: "2677.95",+ price: "0.9267",+ amount: "2498.31",+ currency: "EUR",+ symbol: "BOND",+ exchange_slug: "LSX"+ }+ })++ security = find_trade("trade_republic_event_evt_legacy_bond").entryable.security+ assert_equal "IT0005377152", security.ticker+ assert_nil security.exchange_operating_mic+ end+privatedef create_linked_crypto_account!diff --git a/test/models/trade_republic_account_holdings_processor_test.rb b/test/models/trade_republic_account_holdings_processor_test.rbindex d0a8299813..4efe5ee007 100644--- a/test/models/trade_republic_account_holdings_processor_test.rb+++ b/test/models/trade_republic_account_holdings_processor_test.rb@@ -570,6 +570,211 @@ class TradeRepublicAccountHoldingsProcessorTest < ActiveSupport::TestCaseassert_equal BigDecimal("70"), crypto.account_balanceend+ test "bonds resolve by ISIN and leave the shared BOND listing" do+ Security.stubs(:search_provider).returns([])+ shared = Security.create!(ticker: "BOND", exchange_operating_mic: "XHAM", name: "Mai 2072")+ provider_id = @tr_account.account_provider.id+ # Earlier syncs put both bonds on the shared listing; the French bond+ # overwrote today's Italian snapshot.+ @account.holdings.create!(+ security: shared, date: Date.current - 1, qty: 2677.95, price: 84.04, amount: 225054.92, currency: "EUR",+ external_id: "trade_republic_position_DEHOLD1_IT0005377152_#{Date.current - 1}", account_provider_id: provider_id+ )+ @account.holdings.create!(+ security: shared, date: Date.current, qty: 1000, price: 48.5, amount: 48500, currency: "EUR",+ external_id: "trade_republic_position_DEHOLD1_FR0014001NN8_#{Date.current}", account_provider_id: provider_id+ )++ @tr_account.update!(raw_positions_payload: [+ bond_position(isin: "IT0005377152", name: "ITALIEN 19/40", quantity: "2677.95", price: "0.8404"),+ bond_position(isin: "FR0014001NN8", name: "FRANKREICH 21/72", quantity: "1000", price: "0.485")+ ])+ TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload).process++ assert_not @account.holdings.exists?(security: shared)++ italy = Security.find_by!(ticker: "IT0005377152")+ assert italy.offline?+ assert_equal "ITALIEN 19/40", italy.name+ assert_equal [ Date.current - 1, Date.current ], @account.holdings.where(security: italy).order(:date).pluck(:date)+ assert_equal BigDecimal("2250.5492"), @account.holdings.find_by!(security: italy, date: Date.current).amount++ france = Security.find_by!(ticker: "FR0014001NN8")+ holding = @account.holdings.find_by!(security: france)+ assert_equal BigDecimal("485"), holding.amount+ assert_equal france.id, holding.provider_security_id+ end++ test "bond rematch keeps the bond's own holding and its cost basis on a date collision" do+ shared = Security.create!(ticker: "BOND", exchange_operating_mic: "XHAM", name: "März 2040")+ italy = Security.create!(ticker: "IT0005377152", name: "ITALIEN 19/40", offline: true)+ provider_id = @tr_account.account_provider.id+ date = Date.current - 1+ own = @account.holdings.create!(+ security: italy, date: date, qty: 2677.95, price: 0.8404, amount: 2250.55, currency: "EUR",+ account_provider_id: provider_id+ )+ stale = @account.holdings.create!(+ security: shared, date: date, qty: 2677.95, price: 84.04, amount: 225054.92, currency: "EUR",+ external_id: "trade_republic_position_DEHOLD1_IT0005377152_#{date}", account_provider_id: provider_id,+ cost_basis: 0.9271, cost_basis_source: "manual", cost_basis_locked: true+ )++ @tr_account.update!(raw_positions_payload: [+ bond_position(isin: "IT0005377152", name: "ITALIEN 19/40", quantity: "2677.95", price: "0.8404")+ ])+ assert_difference -> { DebugLogEntry.where(message: "Bond rematch collision kept the bond's own holding market values").count }, 1 do+ TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload).process+ end++ assert_not Holding.exists?(stale.id)+ own.reload+ assert_equal BigDecimal("2250.55"), own.amount+ assert_equal BigDecimal("0.9271"), own.cost_basis+ assert own.cost_basis_locked?+ assert_equal stale.external_id, own.external_id+ assert_nil own.provider_security_id+ end++ test "positions on the legacy BOND listing resolve by ISIN" do+ import_position(isin: "IT0005377152", quantity: "2677.95", price: "0.8404", symbol: "BOND", exchange_slug: "LSX")++ security = @account.holdings.first.security+ assert_equal "IT0005377152", security.ticker+ assert_nil security.exchange_operating_mic+ end++ test "bond rematch leaves share positions alone" do+ other = Security.create!(ticker: "OTHER", name: "Other")+ holding = @account.holdings.create!(+ security: other, date: Date.current - 1, qty: 1, price: 10, amount: 10, currency: "EUR",+ external_id: "trade_republic_position_DEHOLD1_US0378331005_#{Date.current - 1}",+ account_provider_id: @tr_account.account_provider.id+ )++ import_position(isin: "US0378331005", quantity: "1", price: "183.94")++ assert_equal other, holding.reload.security+ end++ test "the prefetcher does not look up the legacy BOND listing" do+ Setting.stubs(:enabled_securities_providers).returns([ "twelve_data" ])+ Security.stubs(:provider_for).returns(Object.new)+ Security.expects(:search_provider).never+ @tr_account.update!(+ current_balance: 2250.55,+ raw_positions_payload: [+ position_payload(isin: "IT0005377152", quantity: "2677.95", price: "0.8404", symbol: "BOND", exchange_slug: "LSX")+ ],+ raw_timeline_payload: [+ {+ "id" => "evt_legacy_bond",+ "timestamp" => "2025-11-18T11:19:31Z",+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => {+ "isin" => "IT0005377152", "quantity" => "2677.95", "price" => "0.9267", "amount" => "2498.31",+ "currency" => "EUR", "symbol" => "BOND", "exchange_slug" => "LSX"+ }+ }+ ]+ )++ TradeRepublicAccount::Processor.new(@tr_account.reload).process++ assert_not Security.exists?(ticker: "BOND")+ assert_equal "IT0005377152", @account.holdings.first.security.ticker+ end++ test "legacy BOND positions point provider_security_id at the bond's own security" do+ shared = Security.create!(ticker: "BOND", exchange_operating_mic: "XHAM", name: "März 2040")+ italy = Security.create!(ticker: "IT0005377152", name: "März 2040", offline: true, offline_reason: "trade_republic_isin")+ # import_holding already moved today's row in an earlier sync, but kept+ # the shared listing as the provider's security.+ holding = @account.holdings.create!(+ security: italy, provider_security: shared, date: Date.current, qty: 2677.95, price: 0.8404, amount: 2250.55,+ currency: "EUR", external_id: "trade_republic_position_DEHOLD1_IT0005377152_#{Date.current}",+ account_provider_id: @tr_account.account_provider.id+ )++ import_position(isin: "IT0005377152", quantity: "2677.95", price: "0.8404", symbol: "BOND", exchange_slug: "LSX")++ assert_equal italy.id, holding.reload.provider_security_id+ assert_not holding.security_remapped?+ end++ test "bond rematch keeps a holding the user remapped" do+ shared = Security.create!(ticker: "BOND", exchange_operating_mic: "XHAM", name: "März 2040")+ holding = @account.holdings.create!(+ security: shared, date: Date.current - 1, qty: 10, price: 1, amount: 10, currency: "EUR",+ external_id: "trade_republic_position_DEHOLD1_IT0005377152_#{Date.current - 1}",+ account_provider_id: @tr_account.account_provider.id, security_locked: true+ )++ @tr_account.update!(raw_positions_payload: [+ bond_position(isin: "IT0005377152", name: "ITALIEN 19/40", quantity: "10", price: "0.8404")+ ])+ TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload).process++ assert_equal shared, holding.reload.security+ end++ test "removes holdings calculated on the shared BOND listing" do+ Security.stubs(:search_provider).returns([])+ shared = Security.create!(ticker: "BOND", exchange_operating_mic: "XHAM", name: "März 2040")+ calculated = @account.holdings.create!(+ security: shared, date: Date.current - 30, qty: 2677.95, price: 84.04, amount: 225054.92, currency: "EUR"+ )+ locked = @account.holdings.create!(+ security: shared, date: Date.current - 31, qty: 2677.95, price: 84.04, amount: 225054.92, currency: "EUR",+ security_locked: true+ )+ other_account = @family.accounts.create!(+ name: "Other broker", balance: 0, currency: "EUR", accountable: Investment.new+ )+ other = other_account.holdings.create!(+ security: shared, date: Date.current - 30, qty: 1, price: 1, amount: 1, currency: "EUR"+ )+ share = @account.holdings.create!(+ security: Security.create!(ticker: "BAS", exchange_operating_mic: "XETR", name: "BASF"),+ date: Date.current - 30, qty: 1, price: 1, amount: 1, currency: "EUR"+ )+ bond_ticker_elsewhere = @account.holdings.create!(+ security: Security.create!(ticker: "BOND", exchange_operating_mic: "ARCX", name: "PIMCO Active Bond ETF"),+ date: Date.current - 30, qty: 1, price: 1, amount: 1, currency: "EUR"+ )++ # A sold bond is no longer a position; its calculated rows go as well.+ assert_difference -> { DebugLogEntry.where(provider_key: "trade_republic").count }, 1 do+ import_position(isin: "IE00B5BMR087", quantity: "2", price: "511.96")+ end++ assert_not Holding.exists?(calculated.id)+ assert Holding.exists?(locked.id)+ assert Holding.exists?(other.id)+ assert Holding.exists?(share.id)+ assert Holding.exists?(bond_ticker_elsewhere.id)+ end++ test "bond rematch keeps the provider security of a locked holding already on the bond" do+ shared = Security.create!(ticker: "BOND", exchange_operating_mic: "XHAM", name: "März 2040")+ italy = Security.create!(ticker: "IT0005377152", name: "ITALIEN 19/40", offline: true,+ offline_reason: "trade_republic_isin")+ holding = @account.holdings.create!(+ security: italy, provider_security: shared, date: Date.current - 1, qty: 10, price: 1, amount: 10,+ currency: "EUR", external_id: "trade_republic_position_DEHOLD1_IT0005377152_#{Date.current - 1}",+ account_provider_id: @tr_account.account_provider.id, security_locked: true+ )++ @tr_account.update!(raw_positions_payload: [+ bond_position(isin: "IT0005377152", name: "ITALIEN 19/40", quantity: "10", price: "0.8404")+ ])+ TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload).process++ assert_equal shared.id, holding.reload.provider_security_id+ assert_equal italy, holding.security+ end+privatedef import_position(isin:, quantity:, price:, average_cost: nil, symbol: nil, exchange_slug: nil)@@ -579,6 +784,17 @@ class TradeRepublicAccountHoldingsProcessorTest < ActiveSupport::TestCaseTradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload).processend+ def bond_position(isin:, name:, quantity:, price:)+ {+ "isin" => isin,+ "name" => name,+ "category" => "interest_products",+ "instrument_type" => "bond",+ "quantity" => quantity,+ "price" => price+ }+ end+def position_payload(isin:, quantity:, price:, average_cost: nil, symbol: nil, exchange_slug: nil){"isin" => isin,diff --git a/test/models/trade_republic_client_test.rb b/test/models/trade_republic_client_test.rbindex 775808650b..793b3cdfb5 100644--- a/test/models/trade_republic_client_test.rb+++ b/test/models/trade_republic_client_test.rb@@ -1470,6 +1470,49 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseassert Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(stored, 25.hours.from_now)end+ test "detail backfill marks a stored trade that stays incomplete" do+ freeze_time+ event = {+ "id" => "trade-1",+ "timestamp" => 2.days.ago.iso8601,+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => { "amount" => -100.0, "currency" => "EUR" }+ }+ @client.define_singleton_method(:subscribe) { |_websocket, **_payload| { "sections" => [] } }++ events, = @client.send(:enrich_timeline_details, Object.new, [], enrich_events: [ event ])++ stored = events.find { |candidate| candidate["id"] == "trade-1" }+ assert_equal Time.current.iso8601, stored.dig("detail", Provider::TradeRepublicClient::DETAIL_BACKFILL_ATTEMPTED_AT_KEY)+ end++ test "detail backfill leaves no attempt marker on a trade it completes" do+ event = {+ "id" => "trade-1",+ "timestamp" => 2.days.ago.iso8601,+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => { "amount" => -1024.92, "currency" => "EUR" }+ }+ @client.define_singleton_method(:subscribe) do |_websocket, **_payload|+ { "sections" => [+ { "title" => "Overview", "type" => "table", "data" => [+ { "title" => "Shares", "detail" => { "text" => "2" } },+ { "title" => "Share price", "detail" => { "text" => "€511.96" } },+ { "title" => "Total", "detail" => { "text" => "€1,024.92" } }+ ] },+ { "data" => [ { "detail" => { "action" => { "payload" => { "instrumentId" => "IE00B5BMR087" } } } } ] }+ ] }+ end++ events, = @client.send(:enrich_timeline_details, Object.new, [], enrich_events: [ event ])++ stored = events.find { |candidate| candidate["id"] == "trade-1" }+ assert Provider::TradeRepublicClient.trade_detail_complete?(stored)+ assert_nil stored.dig("detail", Provider::TradeRepublicClient::DETAIL_BACKFILL_ATTEMPTED_AT_KEY)+ end+test "price backfill stops retrying once the trade is older than the retry window" dotrade = {"category" => "orderExecution",@@ -1691,6 +1734,24 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseassert_equal "US0378331005", enriched.find { |event| event["id"] == "dividend-1" }.dig("detail", "isin")end+ test "detail backfill marks a stored dividend that stays without details" do+ freeze_time+ stored = {+ "id" => "dividend-1",+ "timestamp" => "2024-12-27T10:00:00Z",+ "eventType" => "SSP_CORPORATE_ACTION_CASH",+ "category" => "DIVIDEND",+ "status" => "EXECUTED",+ "detail" => { "amount" => 4.3, "currency" => "EUR" }+ }+ @client.define_singleton_method(:subscribe) { |_websocket, **_payload| { "sections" => [] } }++ enriched, = @client.send(:enrich_timeline_details, Object.new, [], enrich_events: [ stored ])++ dividend = enriched.find { |event| event["id"] == "dividend-1" }+ assert_equal Time.current.iso8601, dividend.dig("detail", Provider::TradeRepublicClient::DETAIL_BACKFILL_ATTEMPTED_AT_KEY)+ end+test "trade savings saveback and round-up events request timeline details" dorequested = []@client.define_singleton_method(:subscribe) do |_websocket, **payload|@@ -2002,7 +2063,9 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseenrich_events: [ { "id" => "fail-soft", "eventType" => "SAVINGS_PLAN_INVOICE_CREATED" } ])- assert_empty enriched+ # The failed attempt is recorded, so the backlog moves on to other events.+ assert_equal [ "fail-soft" ], enriched.map { |event| event["id"] }+ assert enriched.first.dig("detail", Provider::TradeRepublicClient::DETAIL_BACKFILL_ATTEMPTED_AT_KEY).present?assert_equal [ "detail fetch failed for event fail-soft" ], warningsassert_raises(Provider::TradeRepublicClient::Timeout) do@@ -2312,8 +2375,400 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseassert_equal "XETR", symbols.dig("NL0000303709", "exchange_slug")end+ test "bonds skip the shared BOND listing and are named by issuer, coupon and maturity" do+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ requested << payload[:type]+ case payload[:type]+ when "instrument"+ {+ "name" => "ITALIEN 19/40",+ "shortName" => "Mar 2040",+ "typeId" => "bond",+ "bondInfo" => { "issuerName" => "Italy", "interestRate" => 0.031, "interestRateType" => "FIXED_INTEREST_RATE" },+ "exchanges" => [+ { "slug" => "LSX", "symbolAtExchange" => "BOND", "active" => true },+ { "slug" => "XFRA", "symbolAtExchange" => "FIT537715", "active" => false }+ ]+ }+ when "ticker"+ { "last" => { "price" => "84.04" } }+ else+ {}+ end+ end++ positions, warnings = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "bonds", "positions" => [+ { "instrumentId" => "IT0005377152", "name" => "März 2040", "netSize" => "2677.95", "averageBuyIn" => "0.927073" }+ ] }+ ]+ }, known_instrument_symbols: { "IT0005377152" => { "symbol" => "BOND", "exchange_slug" => "LSX" } })++ assert_empty warnings+ assert_includes requested, "instrument"+ position = positions.first+ assert_equal "Italy 3.1% Mar 2040", position["name"]+ assert_equal "bond", position["instrument_type"]+ assert_nil position["symbol"]+ assert_nil position["exchange_slug"]+ end++ test "bonds keep the portfolio name when the instrument subscription fails" do+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ raise Provider::TradeRepublicClient::ProviderUnavailable, "instrument unavailable" if payload[:type] == "instrument"++ { "last" => { "price" => "84.04" } }+ end++ positions, = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "bonds", "positions" => [+ { "instrumentId" => "IT0005377152", "name" => "März 2040", "netSize" => "2677.95" }+ ] }+ ]+ })++ assert_equal "März 2040", positions.first["name"]+ assert_equal "bond", positions.first["instrument_type"]+ end++ test "pick_instrument_exchange_symbol ignores bond listings" do+ payload = {+ "typeId" => "bond",+ "exchanges" => [ { "slug" => "LSX", "symbolAtExchange" => "BOND", "active" => true } ]+ }++ assert_nil @client.send(:pick_instrument_exchange_symbol, payload, "FR0014001NN8")+ end++ test "normalize_event_detail reads a bond purchase from the nested breakdown" do+ detail = @client.send(:normalize_event_detail, bond_purchase_detail, item: { "title" => "März 2040", "subtitle" => "Kauforder" })++ assert_equal "IT0005377152", detail["isin"]+ assert_equal "2677.95", detail["quantity"]+ assert_equal "0.9267", detail["price"]+ assert_equal "2498.31", detail["amount"]+ assert_equal "1.0", detail["fees"]+ assert_equal "bond", detail["instrument_type"]+ assert_equal "2481.66", (BigDecimal(detail["quantity"]) * BigDecimal(detail["price"])).round(2).to_s("F")+ end++ test "normalize_event_detail signs a bond sale negative" do+ detail = @client.send(:normalize_event_detail, bond_purchase_detail, item: { "title" => "März 2040", "subtitle" => "Verkaufsorder" })++ assert_equal "-2677.95", detail["quantity"]+ end++ test "share trades do not pick up bond titles" do+ detail = @client.send(:normalize_event_detail, {+ "sections" => [+ { "title" => "Übersicht", "data" => [+ { "title" => "Aktien", "detail" => { "text" => "2" } },+ { "title" => "Quotation", "detail" => { "text" => "50 %" } },+ { "title" => "Summe", "detail" => { "text" => "9,99 €" } },+ { "title" => "Gesamt", "detail" => { "text" => "1.024,92 €" } }+ ] },+ { "data" => [ { "detail" => { "action" => { "payload" => { "instrumentId" => "IE00B5BMR087" } } } } ] }+ ]+ }, item: { "title" => "Core S&P 500", "subtitle" => "Kauforder" })++ assert_equal "1024.92", detail["amount"]+ assert_equal "512.46", detail["price"]+ assert_nil detail["instrument_type"]+ end++ test "rows of a nested untitled table do not override the share trade overview" do+ breakdown = {+ "sections" => [+ { "type" => "table", "data" => [+ { "title" => "Aktien", "detail" => { "text" => "99" } },+ { "title" => "Kurs", "detail" => { "text" => "1,00 €" } },+ { "title" => "Gesamt", "detail" => { "text" => "5,00 €" } }+ ] }+ ]+ }+ detail = @client.send(:normalize_event_detail, {+ "sections" => [+ { "title" => "Übersicht", "type" => "table", "data" => [+ { "title" => "Aktien", "detail" => { "text" => "2" } },+ { "title" => "Kurs", "detail" => { "text" => "511,96 €" } },+ {+ "title" => "Transaktion",+ "detail" => { "text" => "1.023,92 €", "action" => { "type" => "infoPage", "payload" => breakdown } }+ },+ { "title" => "Gesamt", "detail" => { "text" => "1.024,92 €" } }+ ] },+ { "data" => [ { "detail" => { "action" => { "payload" => { "instrumentId" => "IE00B5BMR087" } } } } ] }+ ]+ }, item: { "title" => "Core S&P 500", "subtitle" => "Kauforder" })++ assert_equal "2.0", detail["quantity"]+ assert_equal "511.96", detail["price"]+ assert_equal "1024.92", detail["amount"]+ end++ test "a nested untitled table does not supply a missing share trade price" do+ fx_breakdown = {+ "sections" => [+ { "type" => "table", "data" => [ { "title" => "Kurs", "detail" => { "text" => "1,0850" } } ] }+ ]+ }+ detail = @client.send(:normalize_event_detail, {+ "sections" => [+ { "title" => "Übersicht", "type" => "table", "data" => [+ { "title" => "Aktien", "detail" => { "text" => "2" } },+ {+ "title" => "Wechselkurs",+ "detail" => { "text" => "1,0850", "action" => { "type" => "infoPage", "payload" => fx_breakdown } }+ },+ { "title" => "Gesamt", "detail" => { "text" => "1.024,92 €" } }+ ] }+ ]+ }, item: { "title" => "Core S&P 500", "subtitle" => "Kauforder" })++ assert_equal "512.46", detail["price"]+ end++ test "normalize_event_detail reads an English bond purchase" do+ # Sure connects with locale "en", so this is the detail it actually receives.+ detail = @client.send(:normalize_event_detail, bond_purchase_detail_en, item: { "title" => "Mar 2040", "subtitle" => "Buy Order" })++ assert_equal "IT0005377152", detail["isin"]+ assert_equal "2677.95", detail["quantity"]+ assert_equal "0.9267", detail["price"]+ assert_equal "2498.31", detail["amount"]+ assert_equal "1.0", detail["fees"]+ assert_equal "bond", detail["instrument_type"]+ end++ test "an English bond purchase takes its total from the breakdown" do+ raw = bond_purchase_detail_en+ raw["sections"][1]["data"].reject! { |row| row["title"] == "Total" }++ detail = @client.send(:normalize_event_detail, raw, item: { "title" => "Mar 2040", "subtitle" => "Buy Order" })++ assert_equal "2498.31", detail["amount"]+ end++ test "bond_name combines issuer, fixed coupon and maturity" do+ italy = { "name" => "ITALIEN 19/40", "shortName" => "Mar 2040",+ "bondInfo" => { "issuerName" => "Italy", "interestRate" => "0.031", "interestRateType" => "FIXED_INTEREST_RATE" } }+ france = { "name" => "FRANKREICH 21/72", "shortName" => "May 2072",+ "bondInfo" => { "issuerName" => "France", "interestRate" => 0.005, "interestRateType" => "FIXED_INTEREST_RATE" } }+ zero = { "shortName" => "Feb 2030",+ "bondInfo" => { "issuerName" => "Germany", "interestRate" => "0", "interestRateType" => "FIXED_INTEREST_RATE" } }++ assert_equal "Italy 3.1% Mar 2040", @client.send(:bond_name, italy)+ assert_equal "France 0.5% May 2072", @client.send(:bond_name, france)+ assert_equal "Germany 0% Feb 2030", @client.send(:bond_name, zero)+ end++ test "bond_name leaves out a coupon that is not fixed or not a number" do+ floating = { "name" => "ITALIEN 19/40", "shortName" => "Mar 2040",+ "bondInfo" => { "issuerName" => "Italy", "interestRate" => "0.031", "interestRateType" => "FLOATING_INTEREST_RATE" } }+ unparseable = { "name" => "ITALIEN 19/40", "shortName" => "Mar 2040",+ "bondInfo" => { "issuerName" => "Italy", "interestRate" => "n/a", "interestRateType" => "FIXED_INTEREST_RATE" } }++ assert_equal "Italy Mar 2040", @client.send(:bond_name, floating)+ assert_equal "Italy Mar 2040", @client.send(:bond_name, unparseable)+ end++ test "bond_name falls back to the instrument name without an issuer" do+ assert_equal "ITALIEN 19/40", @client.send(:bond_name, { "name" => "ITALIEN 19/40", "shortName" => "Mar 2040" })+ assert_equal "ITALIEN 19/40", @client.send(:bond_name, { "name" => "ITALIEN 19/40", "shortName" => "Mar 2040", "bondInfo" => "n/a" })+ assert_nil @client.send(:bond_name, nil)+ end++ test "bond_placeholder_listing? only matches BOND on LSX" do+ assert Provider::TradeRepublicClient.bond_placeholder_listing?("BOND", "LSX")+ assert Provider::TradeRepublicClient.bond_placeholder_listing?(" bond ", "lsx")+ assert_not Provider::TradeRepublicClient.bond_placeholder_listing?("BOND", "XETR")+ assert_not Provider::TradeRepublicClient.bond_placeholder_listing?("BAS", "LSX")+ end++ test "enrich_trade_instrument_symbols does not look up bond trades" do+ looked_up = []+ @client.define_singleton_method(:instrument_exchange_symbol) do |_websocket, isin|+ looked_up << isin+ nil+ end+ @client.define_singleton_method(:instrument_name) { |_websocket, _isin| "ITALIEN 19/40" }+ unresolved = []+ events = [+ {+ "id" => "buy-bond",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "category" => "orderExecution",+ "detail" => { "isin" => "IT0005377152", "quantity" => "2677.95", "instrument_type" => "bond" }+ }+ ]++ @client.send(:enrich_trade_instrument_symbols, Object.new, events, unresolved: unresolved)++ assert_empty looked_up+ assert_empty unresolved+ assert_nil events.first.dig("detail", "symbol")+ assert_equal "ITALIEN 19/40", events.first.dig("detail", "instrument_name")+ end++ test "enrich_trade_instrument_symbols stamps the instrument name on bond trades once per ISIN" do+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ requested << payload[:id] if payload[:type] == "instrument"+ next {} unless payload[:id] == "IT0005377152"++ {+ "name" => "ITALIEN 19/40",+ "shortName" => "Mar 2040",+ "typeId" => "bond",+ "bondInfo" => { "issuerName" => "Italy", "interestRate" => "0.031", "interestRateType" => "FIXED_INTEREST_RATE" }+ }+ end+ bond = ->(id, isin, extra = {}) {+ {+ "id" => id,+ "eventType" => "TRADING_TRADE_EXECUTED",+ "category" => "orderExecution",+ "detail" => { "isin" => isin, "quantity" => "1000", "instrument_type" => "bond" }.merge(extra)+ }+ }+ events = [+ bond.call("buy", "IT0005377152"),+ bond.call("sell", "IT0005377152"),+ bond.call("named", "FR0014001NN8", "instrument_name" => "FRANKREICH 21/72"),+ bond.call("unknown", "DE0001102580")+ ]++ @client.send(:enrich_trade_instrument_symbols, Object.new, events)++ assert_equal %w[IT0005377152 DE0001102580], requested+ assert_equal [ "Italy 3.1% Mar 2040", "Italy 3.1% Mar 2040", "FRANKREICH 21/72", nil ],+ events.map { |event| event.dig("detail", "instrument_name") }+ end++ test "bond instrument names stay within the instrument lookup budget" do+ requested = 0+ @client.define_singleton_method(:subscribe) do |_websocket, *_args, **_kwargs|+ requested += 1+ { "name" => "Bond" }+ end+ events = (1..3).map do |index|+ { "id" => "buy-#{index}", "detail" => { "isin" => "XS000000000#{index}", "instrument_type" => "bond" } }+ end++ @client.send(:stamp_bond_instrument_names!, Object.new, events, budget: 2)++ assert_equal 2, requested+ assert_nil events.last.dig("detail", "instrument_name")+ end++ test "bond names already looked up are stamped after the lookup budget is spent" do+ @client.define_singleton_method(:instrument_name) { |_websocket, isin| "Bond #{isin}" }+ events = [+ { "id" => "buy-a", "detail" => { "isin" => "XS0000000001", "instrument_type" => "bond" } },+ { "id" => "buy-b", "detail" => { "isin" => "XS0000000002", "instrument_type" => "bond" } },+ { "id" => "sell-a", "detail" => { "isin" => "XS0000000001", "instrument_type" => "bond" } }+ ]++ @client.send(:stamp_bond_instrument_names!, Object.new, events, budget: 1)++ assert_equal [ "Bond XS0000000001", nil, "Bond XS0000000001" ],+ events.map { |event| event.dig("detail", "instrument_name") }+ end+private+ # Same shape as bond_purchase_detail, in English, as Sure receives it.+ def bond_purchase_detail_en+ row = ->(title, text) { { "title" => title, "detail" => { "text" => text, "type" => "text" }, "style" => "plain" } }+ breakdown = {+ "id" => "00000000-0000-0000-0000-000000000000",+ "sections" => [+ { "title" => "Transaction", "type" => "title" },+ { "type" => "table", "data" => [+ row.call("Face value", "€2,677.95"),+ row.call("Quotation", "92.67 %"),+ row.call("Accrued interest", "€18.35"),+ row.call("Total", "€2,498.31")+ ] }+ ]+ }++ {+ "id" => "bond-purchase-en",+ "sections" => [+ {+ "title" => "You invested €2,498.31",+ "type" => "header",+ "data" => { "subtitleText" => "18 Nov 2025 · 11:19 AM", "status" => "executed" },+ "action" => { "type" => "instrumentDetail", "payload" => "IT0005377152" }+ },+ { "title" => "Overview", "type" => "table", "data" => [+ { "title" => "Buy", "detail" => { "text" => "Executed", "functionalStyle" => "EXECUTED", "type" => "status" } },+ row.call("Asset", "Mar 2040"),+ {+ "title" => "Transaction",+ "detail" => {+ "text" => "€2,481.66",+ "type" => "text",+ "action" => { "type" => "infoPage", "payload" => breakdown, "displayMode" => "bottomSheet" }+ }+ },+ row.call("Fee", "€1.00"),+ row.call("Total", "€2,498.31")+ ] }+ ]+ }+ end++ # Trimmed from a real Trade Republic bond purchase shared in #4012.+ def bond_purchase_detail+ row = ->(title, text) { { "title" => title, "detail" => { "text" => text, "type" => "text" }, "style" => "plain" } }+ breakdown = {+ "id" => "00000000-0000-0000-0000-000000000000",+ "sections" => [+ { "title" => "Transaktion", "type" => "title" },+ { "type" => "table", "data" => [+ row.call("Nennwert", "2.677,95 €"),+ row.call("Quotation", "92,67 %"),+ row.call("Stückzinsen", "18,35 €"),+ row.call("Summe", "2.498,31 €")+ ] }+ ]+ }++ {+ "id" => "bond-purchase",+ "sections" => [+ {+ "title" => "Du hast 2.498,31 € investiert",+ "type" => "header",+ "data" => { "subtitleText" => "18 Nov. 2025 · 11:19", "status" => "executed" },+ "action" => { "type" => "instrumentDetail", "payload" => "IT0005377152" }+ },+ { "title" => "Übersicht", "type" => "table", "data" => [+ { "title" => "Kauf", "detail" => { "text" => "Ausgeführt", "functionalStyle" => "EXECUTED", "type" => "status" } },+ row.call("Asset", "März 2040"),+ {+ "title" => "Transaktion",+ "detail" => {+ "text" => "2.481,66 €",+ "type" => "text",+ "action" => { "type" => "infoPage", "payload" => breakdown, "displayMode" => "bottomSheet" }+ }+ },+ row.call("Gebühr", "1,00 €"),+ row.call("Summe", "2.498,31 €")+ ] }+ ]+ }+ end+# Trimmed from a real Trade Republic stock bonus (ACQUISITION_TRADE_PERK).def stock_bonus_detailrow = ->(title, text) { { "title" => title, "detail" => { "text" => text, "type" => "text" }, "style" => "plain" } }diff --git a/test/models/trade_republic_item_importer_test.rb b/test/models/trade_republic_item_importer_test.rbindex d963746181..9a23479526 100644--- a/test/models/trade_republic_item_importer_test.rb+++ b/test/models/trade_republic_item_importer_test.rb@@ -1074,6 +1074,43 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCaseassert_equal [ "incomplete-ok" ], enrich_idsend+ test "detail enrichment tries never-attempted events first, then the least recently attempted" do+ attempted_key = Provider::TradeRepublicClient::DETAIL_BACKFILL_ATTEMPTED_AT_KEY+ incomplete = ->(id, timestamp, attempted_at = nil) {+ {+ "id" => id,+ "timestamp" => timestamp,+ "eventType" => "TRADING_TRADE_EXECUTED",+ "category" => "orderExecution",+ "detail" => { "amount" => -100.0, attempted_key => attempted_at }.compact+ }+ }+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-ROTATE",+ currency: "EUR",+ raw_timeline_payload: [+ incomplete.call("old-recent-attempt", "2024-01-01T10:00:00Z", 1.hour.ago.iso8601),+ incomplete.call("old-early-attempt", "2024-02-01T10:00:00Z", 2.days.ago.iso8601),+ incomplete.call("new-never-attempted", "2025-11-18T11:19:31Z"),+ {+ "id" => "needs-price",+ "timestamp" => 1.day.ago.iso8601,+ "eventType" => "TRADING_TRADE_EXECUTED",+ "category" => "orderExecution",+ "detail" => { "isin" => "US0378331005", "quantity" => "1", "amount" => -100.0 }+ }+ ]+ )++ enrich_ids = TradeRepublicItem::Importer.new(@item, provider: mock("provider"))+ .send(:events_needing_detail_enrichment)+ .map { |event| event["id"] }++ assert_equal %w[new-never-attempted needs-price old-early-attempt old-recent-attempt], enrich_ids+ end+test "events needing detail enrichment include complete trades missing share price" do@item.trade_republic_accounts.create!(kind: "portfolio",@@ -1234,7 +1271,7 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCaseportfolio.reload.raw_timeline_payload.first.dig("detail", Provider::TradeRepublicClient::SYMBOL_LOOKUP_FIRST_ATTEMPTED_AT_KEY)end- test "isins_needing_symbol_lookup skips trades that already have a ticker" do+ test "isins_needing_symbol_lookup skips trades that already have a ticker and bonds" do@item.trade_republic_accounts.create!(kind: "portfolio",name: "Portfolio",@@ -1258,6 +1295,12 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCase"quantity" => "1","amount" => "10"}+ },+ {+ "id" => "bond",+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => { "isin" => "IT0005377152", "quantity" => "2677.95", "amount" => "2498.31", "instrument_type" => "bond" }}])