The personal finance app for everyone (by everyone)
Ruby
Improve Trade Republic sync: routing, tickers, fees, and timeline quality (#3669)
Niels Eulinka83321c1cf6d
diff --git a/app/models/provider/trade_republic_client.rb b/app/models/provider/trade_republic_client.rbindex f98773f0c9..1fe28137dd 100644--- a/app/models/provider/trade_republic_client.rb+++ b/app/models/provider/trade_republic_client.rb@@ -35,51 +35,23 @@ class Provider::TradeRepublicClient503 => TransientProviderError,504 => TransientProviderError}.freeze- DETAIL_CATEGORIES = %w[orderExecution PAYMENT_RECEIVED POC_CREATED INTEREST_PAYOUT_CREATED DIVIDEND].freeze- EVENT_TYPE_CATEGORIES = {- "TRADING_TRADE_EXECUTED" => "orderExecution",- "TRADE_INVOICE" => "orderExecution",- "ORDER_EXECUTED" => "orderExecution",- "CRYPTO_INVOICE" => "orderExecution",- "SAVINGS_PLAN_EXECUTED" => "orderExecution",- "TRADING_SAVINGSPLAN_EXECUTED" => "orderExecution",- "PRIVATE_MARKET_FUND_TRADE_EXECUTED" => "orderExecution",- "IPO_TRADE_EXECUTED" => "orderExecution",- "BANK_TRANSACTION_INCOMING" => "PAYMENT_RECEIVED",- "INCOMING_TRANSFER" => "PAYMENT_RECEIVED",- "INCOMING_TRANSFER_DELEGATION" => "PAYMENT_RECEIVED",- "PAYMENT_INBOUND" => "PAYMENT_RECEIVED",- "PAYMENT_INBOUND_SEPA_DIRECT_DEBIT" => "PAYMENT_RECEIVED",- "PAYMENT_INBOUND_APPLE_PAY" => "PAYMENT_RECEIVED",- "BANK_TRANSACTION_OUTGOING" => "POC_CREATED",- "BANK_TRANSACTION_OUTGOING_DIRECT_DEBIT" => "POC_CREATED",- "OUTGOING_TRANSFER" => "POC_CREATED",- "OUTGOING_TRANSFER_DELEGATION" => "POC_CREATED",- "PAYMENT_OUTBOUND" => "POC_CREATED",- "CARD_TRANSACTION" => "POC_CREATED",- "card_successful_transaction" => "POC_CREATED",- # Trade Republic currently uses CARD_CASH_BACK for some card purchases- # (for example, Marktkauf), not only for actual cashback credits. The- # signed provider amount confirms these are cash outflows.- "CARD_CASH_BACK" => "POC_CREATED",- "card_refund" => "PAYMENT_RECEIVED",- "CARD_REFUND" => "PAYMENT_RECEIVED",- "SPARE_CHANGE_AGGREGATE" => "POC_CREATED",- "SAVEBACK_AGGREGATE" => "POC_CREATED",- "BANK_TRANSACTION_OUTGOING_SCHEDULED" => "POC_CREATED",- "CARD_ATM_WITHDRAWAL" => "POC_CREATED",- "SSP_CORPORATE_ACTION_CASH" => "DIVIDEND",- "ssp_corporate_action_invoice_cash" => "DIVIDEND",- "SSP_CORPORATE_ACTION_CASH_NON_DIVIDEND" => "PAYMENT_RECEIVED",- "DIVIDEND" => "DIVIDEND",- "CREDIT" => "DIVIDEND",- "INTEREST_PAYOUT" => "INTEREST_PAYOUT_CREATED",- "INTEREST_PAYOUT_CREATED" => "INTEREST_PAYOUT_CREATED",- "TAX_REFUND" => "PAYMENT_RECEIVED",- "ssp_tax_correction_invoice" => "PAYMENT_RECEIVED",- "SSP_TAX_CORRECTION" => "PAYMENT_RECEIVED",- "CARD_ORDER_FEE" => "POC_CREATED"- }.freeze+ # Categories/event types that need timelineDetailV2 for ISIN and quantity.+ # Ordinary cash movements (card payments, transfers, interest) use the+ # timeline list amount only and must not consume the detail budget.+ TRADE_DETAIL_CATEGORY = "orderExecution"+ TRADE_DETAIL_EVENT_TYPES = %w[+ SAVEBACK_AGGREGATE+ SPARE_CHANGE_AGGREGATE+ ].freeze+ # New dividends also fetch timelineDetailV2 so provider_detail keeps the+ # ISIN, share count, dividend per share and withholding tax. The imported+ # cash amount still comes from the timeline list.+ DIVIDEND_DETAIL_CATEGORY = Provider::TradeRepublicTimelineEvent::CATEGORY_DIVIDEND+ DIVIDEND_DETAIL_KEYS = %w[isin name quantity dividend_per_share taxes].freeze+ DIVIDEND_PER_SHARE_TITLES = [+ "dividend per share", "dividende pro aktie", "dividend per aandeel", "ausschüttung pro anteil"+ ].freeze+ EVENT_TYPE_CATEGORIES = Provider::TradeRepublicTimelineEvent::EVENT_TYPE_CATEGORIESPORTFOLIO_CATEGORIES = {"stocksAndETFs" => "brokerage","privateMarkets" => "private_markets",@@ -89,10 +61,46 @@ class Provider::TradeRepublicClient}.freezeTICKER_EXCHANGES = %w[LSX BHS TUB SGL BVT].freezeCRYPTO_TICKER_EXCHANGES = %w[BHS TUB SGL BVT LSX].freeze- FEE_TITLES = [ "gebühr", "fee" ].freeze- TAX_TITLES = [ "steuer", "steuern", "tax", "taxes" ].freeze+ # Prefer real venues over Trade Republic's synthetic LSX feed. Skip symbols+ # that merely echo the ISIN (common on TIB).+ INSTRUMENT_EXCHANGE_PREFERENCE = %w[XETR TDG].freeze+ INSTRUMENT_EXCHANGE_LAST_RESORT = %w[LSX].freeze+ INSTRUMENT_SYMBOL_CATEGORIES = %w[stocksAndETFs bonds].freeze+ FEE_TITLES = [+ "gebühr", "fee", "fees", "kosten", "costs", "cost", "commission", "kommission"+ ].freeze+ TAX_TITLES = [ "steuer", "steuern", "tax", "taxes", "belasting" ].freeze+ SHARE_TITLES = [+ "aktien", "anteile", "shares", "aandelen",+ "aktien hinzugefügt", "shares added", "aktien erhalten", "shares received",+ "aktien entfernt", "shares removed", "aktien gesendet", "shares sent"+ ].freeze+ TOTAL_TITLES = [ "gesamt", "total", "totaal", "gesamtbetrag" ].freeze+ PRICE_TITLES = [+ "share price", "aandelenkoers", "aktienkurs", "anteilskurs",+ "execution price", "kurs"+ ].freeze+ SELL_SUBTITLE_MARKERS = %w[sell verkauf verkaufen verkopen].freezeMAX_TIMELINE_PAGES = 50MAX_TIMELINE_DETAILS = 200+ # Reserve this many detail fetches for newly discovered trade events each+ # sync. The remainder drains the oldest stored incomplete events; leftover+ # budget returns to additional new events.+ MAX_TIMELINE_DETAILS_DELTA_RESERVED = 50+ # Unsuccessful price backfills and symbol lookups are retried at most once+ # per RETRY_INTERVAL, and stop once RETRY_WINDOW has passed (since the trade+ # for prices, since the first failed attempt for symbols).+ RETRY_INTERVAL = 1.day+ RETRY_WINDOW = 30.days+ PRICE_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"+ RETRY_MARKER_KEYS = [+ PRICE_BACKFILL_ATTEMPTED_AT_KEY, SYMBOL_LOOKUP_ATTEMPTED_AT_KEY, SYMBOL_LOOKUP_FIRST_ATTEMPTED_AT_KEY+ ].freeze+ # Cap instrument lookups for sold / historical trade ISINs that are absent+ # from the current portfolio snapshot.+ MAX_INSTRUMENT_LOOKUPS = 100MAX_SYNC_RETRIES = 2RETRY_BACKOFF_SECONDS = 0.5LOGIN_SUCCESS_STATES = %w[CONFIRMED COMPLETED APPROVED SUCCESS OK DONE].freeze@@ -268,19 +276,22 @@ class Provider::TradeRepublicClientendend- def sync(session_txt:, known_newest_event_id: nil, timeline_max_pages: MAX_TIMELINE_PAGES)+ def sync(session_txt:, known_newest_event_id: nil, timeline_max_pages: MAX_TIMELINE_PAGES, enrich_events: [], symbol_lookup_isins: [], known_instrument_symbols: {})raise ConfigurationError, "session_txt is required" if session_txt.blank?with_retry dosync_once(session_txt: session_txt,known_newest_event_id: known_newest_event_id,- timeline_max_pages: timeline_max_pages+ timeline_max_pages: timeline_max_pages,+ enrich_events: enrich_events,+ symbol_lookup_isins: symbol_lookup_isins,+ known_instrument_symbols: known_instrument_symbols)endend- def sync_once(session_txt:, known_newest_event_id:, timeline_max_pages:)+ def sync_once(session_txt:, known_newest_event_id:, timeline_max_pages:, enrich_events: [], symbol_lookup_isins: [], known_instrument_symbols: {})session = new_session(session_blob: session_txt)account_response = session.get("/api/v2/auth/account")return Result.new(data: { "status" => "session_expired" }) if [ 401, 403 ].include?(account_response.code.to_i)@@ -318,7 +329,12 @@ class Provider::TradeRepublicClientbeginportfolio = subscribe(websocket, type: "compactPortfolioByType", secAccNo: account["securitiesAccountNumber"])raise MalformedResponse, "Trade Republic portfolio response did not contain categories" unless portfolio.is_a?(Hash) && portfolio.key?("categories")- positions, position_warnings = normalize_positions(websocket, portfolio)+ positions, position_warnings = normalize_positions(+ websocket,+ portfolio,+ sec_acc_no: account["securitiesAccountNumber"],+ known_instrument_symbols: known_instrument_symbols+ )warnings.concat(position_warnings)domain_statuses["portfolio"] = "success"domain_statuses["instrument_metadata"] = position_warnings.empty? ? "success" : "partial"@@ -327,17 +343,32 @@ class Provider::TradeRepublicClientwarnings << "portfolio fetch failed: #{e.message}"end+ known_symbols = self.class.instrument_symbols_from_positions(positions)+ instrument_symbols = known_symbols.dup+ unresolved_symbol_isins = []+events = []newest_event_id = niltimeline_warnings = []timeline_complete = false+ detail_backfill_count = 0begin- events, newest_event_id, timeline_warnings, timeline_complete = collect_all_timeline(+ events, newest_event_id, timeline_warnings, timeline_complete, detail_backfill_count = collect_all_timeline(websocket,known_newest_event_id: known_newest_event_id,- max_pages: timeline_max_pages.to_i+ max_pages: timeline_max_pages.to_i,+ enrich_events: enrich_events+ )+ instrument_symbols = enrich_trade_instrument_symbols(+ websocket,+ events,+ known_symbols: known_symbols,+ extra_isins: symbol_lookup_isins,+ unresolved: unresolved_symbol_isins)warnings.concat(timeline_warnings)+ # Timeline domain reflects list pagination only. Detail backlog drains+ # across later syncs and must not freeze newest_event_id.domain_statuses["timeline"] = timeline_complete ? "success" : "partial"rescue MalformedResponse, ProviderUnavailable => eraise if e.is_a?(TransientProviderError)@@ -354,8 +385,15 @@ class Provider::TradeRepublicClient"available_amount" => decimal_string(money_amount(available_cash)),"currency" => money_currency(available_cash) || money_currency(cash)}.compact),- "positions" => positions, "events" => events, "newest_event_id" => newest_event_id,- "warnings" => warnings, "position_warnings" => position_warnings+ "positions" => positions,+ "events" => events,+ "instrument_symbols" => instrument_symbols,+ "unresolved_symbol_isins" => unresolved_symbol_isins,+ "newest_event_id" => newest_event_id,+ "timeline_pagination_complete" => timeline_complete,+ "detail_backfill_count" => detail_backfill_count,+ "warnings" => warnings,+ "position_warnings" => position_warnings})ensurewebsocket.close@@ -366,6 +404,109 @@ class Provider::TradeRepublicClientclass << selfdef available? = !!defined?(WebSocket::Driver)++ def requires_trade_detail?(item)+ return false unless item.is_a?(Hash)++ item = item.stringify_keys+ category = item["category"].presence || EVENT_TYPE_CATEGORIES[item["eventType"].to_s]+ return true if category.to_s == TRADE_DETAIL_CATEGORY++ TRADE_DETAIL_EVENT_TYPES.include?(item["eventType"].to_s)+ end++ def trade_detail_complete?(event)+ return false unless event.is_a?(Hash)++ detail = event["detail"] || event[:detail]+ return false unless detail.is_a?(Hash)++ detail = detail.stringify_keys+ detail["isin"].present? && detail["quantity"].present?+ end++ def incomplete_trade_detail_event?(event)+ return false unless requires_trade_detail?(event)+ return false unless Provider::TradeRepublicTimelineEvent.importable?(event)++ !trade_detail_complete?(event)+ end++ def dividend_detail_missing?(event)+ return false unless event.is_a?(Hash)++ item = event.stringify_keys+ category = item["category"].presence || EVENT_TYPE_CATEGORIES[item["eventType"].to_s]+ return false unless category.to_s == DIVIDEND_DETAIL_CATEGORY+ return false unless Provider::TradeRepublicTimelineEvent.importable?(item)++ detail = item["detail"]+ !(detail.is_a?(Hash) && detail.stringify_keys["isin"].present?)+ end++ # Complete trades (isin + quantity) that still lack a share price — usually+ # stored before we parsed execution price / fees from timeline details.+ # Trade Republic sometimes publishes the price late, so an unsuccessful+ # attempt is retried at most once per RETRY_INTERVAL until the trade is+ # RETRY_WINDOW old.+ def trade_detail_needs_price_backfill?(event, now = Time.current)+ return false unless trade_detail_missing_price?(event)++ attempted_at = detail_time(event, PRICE_BACKFILL_ATTEMPTED_AT_KEY)+ return true if attempted_at.nil?++ traded_at = parse_time((event["timestamp"] || event[:timestamp]))+ return false if traded_at && traded_at <= now - RETRY_WINDOW++ attempted_at <= now - RETRY_INTERVAL+ 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)+ attempted_at = detail_time(event, SYMBOL_LOOKUP_ATTEMPTED_AT_KEY)+ return true if attempted_at.nil?++ first_attempted_at = detail_time(event, SYMBOL_LOOKUP_FIRST_ATTEMPTED_AT_KEY) || attempted_at+ return false if first_attempted_at <= now - RETRY_WINDOW++ attempted_at <= now - RETRY_INTERVAL+ end++ def trade_detail_missing_price?(event)+ return false unless requires_trade_detail?(event)+ return false unless Provider::TradeRepublicTimelineEvent.importable?(event)+ return false unless trade_detail_complete?(event)++ detail = (event["detail"] || event[:detail]).stringify_keys+ detail["price"].to_s.strip.blank?+ end++ def instrument_symbols_from_positions(positions)+ Array(positions).each_with_object({}) do |position, map|+ next unless position.is_a?(Hash)++ position = position.stringify_keys+ isin = position["isin"].to_s.presence+ symbol = position["symbol"].to_s.strip.presence+ exchange_slug = position["exchange_slug"].to_s.strip.upcase.presence+ next if isin.blank? || symbol.blank? || exchange_slug.blank?+ next if symbol.casecmp?(isin)++ map[isin] = { "symbol" => symbol, "exchange_slug" => exchange_slug }+ end+ end++ def detail_time(event, key)+ detail = (event["detail"] || event[:detail])+ parse_time(detail.stringify_keys[key]) if detail.is_a?(Hash)+ end++ def parse_time(value)+ Time.zone.parse(value.to_s) if value.present?+ rescue ArgumentError+ nil+ endendprivate@@ -521,7 +662,7 @@ class Provider::TradeRepublicClientdef optional_subscribe(websocket, payload)subscribe(websocket, payload)- rescue TransientProviderError+ rescue TransientProviderError, RateLimitedraiserescue Errornil@@ -571,7 +712,9 @@ class Provider::TradeRepublicClientend.joinend- def normalize_positions(websocket, portfolio)+ # `known_instrument_symbols` are exchange tickers stored by earlier syncs;+ # those ISINs skip the instrument subscription.+ def normalize_positions(websocket, portfolio, sec_acc_no: nil, known_instrument_symbols: {})raw_positions = Array(portfolio["categories"]).flat_map do |category|Array(category["positions"]).map { |position| position.merge("categoryType" => category["categoryType"]) }end@@ -587,43 +730,295 @@ class Provider::TradeRepublicClientendendprices = {}+ instruments = {}+ known_symbols = stringify_instrument_symbols(known_instrument_symbols)+ private_market_quotes = private_markets_unit_prices(websocket, sec_acc_no) if valid_positions.any? { |p|+ p["categoryType"].to_s == "privateMarkets"+ }+valid_positions.each do |position|isin = position["instrumentId"].presence || position["isin"]next if prices.key?(isin)+ private_market = position["categoryType"].to_s == "privateMarkets"price = position_price(websocket, isin, position["categoryType"])- prices[isin] = price if price.present?- warnings << "price unavailable for #{isin}; position kept without valuation" if price.blank?+ price = private_market_quotes[isin] if price.blank? && private_market_quotes.present?+ # Private-market funds have no exchange quote. Without a+ # privateMarketsPositions unit price, value them at the average buy-in+ # rather than zero. Other categories keep the unpriced warning.+ price = decimal_string(position["averageBuyIn"] || position["avgCost"]) if price.blank? && private_market++ if price.present?+ prices[isin] = price+ else+ warnings << "price unavailable for #{isin}; position kept without valuation"+ end+ end+ valid_positions.each do |position|+ isin = position["instrumentId"].presence || position["isin"]+ next if instruments.key?(isin)+ next unless INSTRUMENT_SYMBOL_CATEGORIES.include?(position["categoryType"].to_s)++ known = known_symbols[isin]+ instruments[isin] = if known+ { symbol: known["symbol"], exchange_slug: known["exchange_slug"] }+ else+ instrument_exchange_symbol(websocket, isin)+ endendpositions = valid_positions.map do |position|isin = position["instrumentId"].presence || position["isin"]quantity = position["netSize"] || position["quantity"]- { "isin" => isin, "name" => position["name"], "category" => portfolio_category(position["categoryType"]), "quantity" => decimal_string(quantity), "average_cost" => decimal_string(position["averageBuyIn"] || position["avgCost"]), "price" => prices[isin] }.compact+ instrument = instruments[isin] || {}+ {+ "isin" => isin,+ "name" => position["name"],+ "category" => portfolio_category(position["categoryType"]),+ "quantity" => decimal_string(quantity),+ "average_cost" => decimal_string(position["averageBuyIn"] || position["avgCost"]),+ "price" => prices[isin],+ "symbol" => instrument[:symbol],+ "exchange_slug" => instrument[:exchange_slug]+ }.compactend[ positions, warnings ]enddef position_price(websocket, isin, category_type)+ home_exchange = home_instrument_exchange_id(websocket, isin)+ if home_exchange.present?+ price = ticker_last_price(websocket, isin, home_exchange)+ return price if price.present?+ end+exchanges = category_type.to_s == "cryptos" ? CRYPTO_TICKER_EXCHANGES : TICKER_EXCHANGESexchanges.each do |exchange|- ticker = subscribe(websocket, type: "ticker", id: "#{isin}.#{exchange}")- price = ticker.dig("last", "price") if ticker.is_a?(Hash)- return decimal_string(price) if price.present?- rescue Timeout- # A ticker that never answers is instrument-metadata loss, not a- # failed portfolio snapshot. Keep the holding and let the importer- # record the missing valuation instead of retrying the whole sync.- return nil- rescue TransientProviderError, RateLimited- raise- rescue Error- next+ next if exchange == home_exchange++ price = ticker_last_price(websocket, isin, exchange)+ return price if price.present?endnilend+ def home_instrument_exchange_id(websocket, isin)+ home = optional_subscribe(websocket, type: "homeInstrumentExchange", id: isin)+ return nil unless home.is_a?(Hash)++ (home["exchangeId"].presence || home["id"].presence || home["slug"].presence).to_s.strip.upcase.presence+ rescue TransientProviderError, RateLimited+ raise+ rescue Error+ nil+ end++ def ticker_last_price(websocket, isin, exchange)+ ticker = subscribe(websocket, type: "ticker", id: "#{isin}.#{exchange}")+ price = ticker.dig("last", "price") if ticker.is_a?(Hash)+ decimal_string(price) if price.present?+ rescue Timeout+ # A hung ticker feed must not block the rest of the exchange list or the+ # private-markets / cost-basis fallbacks below.+ nil+ rescue TransientProviderError, RateLimited+ raise+ rescue Error+ nil+ end++ # Best-effort PE enrichment. Trade Republic rejects the subscription when+ # the account has no private-markets sleeve — treat that as an empty map.+ def private_markets_unit_prices(websocket, sec_acc_no)+ return {} if sec_acc_no.blank?++ payload = optional_subscribe(websocket, type: "privateMarketsPositions", secAccNo: sec_acc_no)+ return {} unless payload.is_a?(Hash)++ Array(payload["positions"]).each_with_object({}) do |position, prices|+ next unless position.is_a?(Hash)++ isin = position["instrumentId"].presence || position["isin"]+ next if isin.blank?++ unit_price = private_markets_unit_price(position)+ prices[isin] = unit_price if unit_price.present?+ end+ rescue TransientProviderError, RateLimited+ raise+ rescue Error+ {}+ end++ def private_markets_unit_price(position)+ quantity = decimal_string(position["netSize"] || position["quantity"] || position["size"])+ qty = quantity.present? ? BigDecimal(quantity) : nil++ explicit = decimal_string(+ position["unitPrice"] ||+ position["nav"] ||+ position["price"] ||+ position.dig("positionReturn", "price") ||+ position.dig("positionReturn", "unitPrice") ||+ position.dig("quotation", "price")+ )+ return explicit if explicit.present?++ total = money_amount(+ position["positionReturn"] ||+ position["currentValue"] ||+ position["marketValue"] ||+ position["netValue"] ||+ position["value"]+ )+ total_s = decimal_string(total)+ return nil if total_s.blank? || qty.nil? || qty.zero?++ decimal_string(BigDecimal(total_s) / qty)+ rescue ArgumentError+ nil+ end++ # 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)+ return nil unless payload.is_a?(Hash)++ pick_instrument_exchange_symbol(payload, isin)+ rescue TransientProviderError, RateLimited+ raise+ rescue Error+ nil+ end++ # Look up exchange tickers for trade ISINs that are no longer (or never)+ # present in the current portfolio snapshot — e.g. fully sold holdings.+ # `extra_isins` covers stored timeline trades that incremental syncs no+ # longer re-fetch after the newest-event cursor advances.+ # ISINs looked up without a usable symbol are appended to `unresolved`.+ def enrich_trade_instrument_symbols(websocket, events, known_symbols: {}, extra_isins: [], unresolved: [])+ symbols = stringify_instrument_symbols(known_symbols)+ missing_isins = (+ trade_isins_missing_symbols(events, symbols) ++ Array(extra_isins).map { |isin| isin.to_s.presence }.compact+ ).uniq+ missing_isins.reject! { |isin| symbols.key?(isin) }++ looked_up = 0+ missing_isins.each do |isin|+ break if looked_up >= MAX_INSTRUMENT_LOOKUPS++ looked_up += 1+ instrument = instrument_exchange_symbol(websocket, isin)+ symbol = instrument[:symbol].to_s.strip.presence if instrument.is_a?(Hash)+ exchange_slug = instrument[:exchange_slug].to_s.strip.upcase.presence if instrument.is_a?(Hash)+ if symbol.blank? || exchange_slug.blank? || symbol.casecmp?(isin)+ unresolved << isin+ next+ end++ symbols[isin] = { "symbol" => symbol, "exchange_slug" => exchange_slug }+ end++ stamp_instrument_symbols_on_events!(events, symbols)+ symbols+ end++ def trade_isins_missing_symbols(events, known_symbols)+ missing = []+ 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)++ detail = detail.stringify_keys+ isin = 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?++ missing << isin+ end+ missing.uniq+ end++ def stamp_instrument_symbols_on_events!(events, symbols)+ Array(events).each do |event|+ next unless event.is_a?(Hash)++ 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?++ mapping = symbols[isin]+ next unless mapping++ if usable_trade_symbol?(detail["symbol"], isin) && detail["exchange_slug"].to_s.strip.present?+ next+ end++ detail["symbol"] = mapping["symbol"] if detail["symbol"].blank? || !usable_trade_symbol?(detail["symbol"], isin)+ detail["exchange_slug"] = mapping["exchange_slug"] if detail["exchange_slug"].to_s.strip.blank?+ event["detail"] = detail+ end+ events+ end++ def stringify_instrument_symbols(known_symbols)+ Array(known_symbols).each_with_object({}) do |(isin, mapping), map|+ next if isin.blank? || !mapping.is_a?(Hash)++ entry = mapping.stringify_keys+ symbol = entry["symbol"].to_s.strip.presence+ exchange_slug = entry["exchange_slug"].to_s.strip.upcase.presence+ next if symbol.blank? || exchange_slug.blank?+ next if symbol.casecmp?(isin.to_s)++ map[isin.to_s] = { "symbol" => symbol, "exchange_slug" => exchange_slug }+ end+ end++ def usable_trade_symbol?(symbol, isin)+ candidate = symbol.to_s.strip.presence+ return false if candidate.blank?+ return false if candidate.casecmp?(isin.to_s)++ true+ end++ def pick_instrument_exchange_symbol(payload, isin)+ 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"])++ symbol = exchange["symbolAtExchange"].to_s.strip.presence+ next if symbol.blank?+ next if symbol.casecmp?(isin.to_s)++ slug = (exchange["slug"].presence || exchange["exchangeId"].presence || exchange["name"]).to_s.strip.upcase+ next if slug.blank?++ { symbol: symbol, exchange_slug: slug }+ end+ return nil if candidates.empty?++ preferred = INSTRUMENT_EXCHANGE_PREFERENCE.filter_map { |slug| candidates.find { |c| c[:exchange_slug] == slug } }+ return preferred.first if preferred.any?++ non_last_resort = candidates.reject { |c| INSTRUMENT_EXCHANGE_LAST_RESORT.include?(c[:exchange_slug]) }+ return non_last_resort.first if non_last_resort.any?++ candidates.first+ end+def portfolio_category(category_type)PORTFOLIO_CATEGORIES[category_type.to_s] || category_typeend@@ -673,33 +1068,38 @@ class Provider::TradeRepublicClient)end- def collect_all_timeline(websocket, known_newest_event_id:, max_pages:)- transaction_events, transaction_cursor, transaction_warnings, transaction_complete = collect_timeline_topic(+ def collect_all_timeline(websocket, known_newest_event_id:, max_pages:, enrich_events: [])+ transaction_events, transaction_newest, transaction_warnings, transaction_complete = collect_timeline_topic(websocket,topic: "timelineTransactions",known_newest_event_id: known_newest_event_id,max_pages: max_pages)- activity_events, activity_cursor, activity_warnings, activity_complete = collect_timeline_topic(+ activity_events, activity_newest, activity_warnings, activity_complete = collect_timeline_topic(websocket,topic: "timelineActivityLog",known_newest_event_id: known_newest_event_id,max_pages: max_pages)- events = (transaction_events + activity_events).uniq do |event|+ skeleton_events = (transaction_events + activity_events).uniq do |event|event["id"].presence || event.slice("timestamp", "eventType", "title", "subtitle", "detail")end- newest_event = events.max_by { |event| event["timestamp"].to_s }- details_incomplete = (transaction_events.any? && transaction_cursor.nil?) ||- (activity_events.any? && activity_cursor.nil?)- timeline_complete = transaction_complete != false && activity_complete != false &&- !details_incomplete &&- (transaction_warnings + activity_warnings).none? { |warning| warning.start_with?("detail fetch failed") }+ events, detail_warnings, detail_backfill_count = enrich_timeline_details(+ websocket,+ skeleton_events,+ enrich_events: enrich_events+ )+ # Backfilled stored events are older than this sync's pages and must not+ # pull the list cursor backwards.+ newest_event = skeleton_events.max_by { |event| event["timestamp"].to_s }+ # Pagination completeness only — pending details drain on later syncs.+ timeline_complete = transaction_complete != false && activity_complete != false[events,- details_incomplete ? nil : (newest_event&.dig("id") || transaction_cursor || activity_cursor),- transaction_warnings + activity_warnings,- timeline_complete+ newest_event&.dig("id") || transaction_newest || activity_newest,+ transaction_warnings + activity_warnings + detail_warnings,+ timeline_complete,+ detail_backfill_count]end@@ -741,61 +1141,222 @@ class Provider::TradeRepublicClientwarnings << "timeline pagination truncated for #{topic}"complete = falseend- details, resolved_newest_event_id, detail_warnings = resolve_details(websocket, items, newest_event_id, warnings)- [ details, resolved_newest_event_id, detail_warnings, complete ]+ events = items.map { |item| build_skeleton_event(item, warnings: warnings) }+ [ events, newest_event_id, warnings, complete ]end- def resolve_details(websocket, items, newest_event_id, warnings)- events = []+ def build_skeleton_event(item, warnings: nil)+ category = item["category"].presence || EVENT_TYPE_CATEGORIES[item["eventType"].to_s]+ classified = item.merge("category" => category)+ if warnings &&+ item["eventType"].present? &&+ Provider::TradeRepublicTimelineEvent.classify(classified) == :unknown+ warnings << "unsupported timeline event type #{item["eventType"]}"+ end+ build_normalized_event(item, category: category, detail: nil)+ end++ # Shared detail budget: reserve capacity for newly discovered trade and+ # dividend events, drain oldest stored incomplete / price-backfill trades+ # next, then spend any leftover on additional new events. Failed attempts+ # still consume budget so a bad event cannot starve the rest of the queue+ # forever within one sync. Stored dividends are not backfilled.+ def enrich_timeline_details(websocket, events, enrich_events: [])+ warnings = []+ events = Array(events)+ new_candidates = events.select do |event|+ event["id"].present? &&+ (self.class.incomplete_trade_detail_event?(event) || self.class.dividend_detail_missing?(event))+ end+ new_ids = new_candidates.to_set { |event| event["id"].to_s }+ backlog_candidates = Array(enrich_events).select do |event|+ next false unless event.is_a?(Hash)++ item = event.stringify_keys+ next false if item["id"].blank?+ next false if new_ids.include?(item["id"].to_s)++ self.class.incomplete_trade_detail_event?(item) ||+ self.class.trade_detail_needs_price_backfill?(item)+ end++ budget = MAX_TIMELINE_DETAILS+ reserved = [ new_candidates.size, MAX_TIMELINE_DETAILS_DELTA_RESERVED, budget ].min+ primary_new = new_candidates.first(reserved)+ remaining_new = new_candidates.drop(reserved)+ remaining_budget = budget - primary_new.size+ backlog_batch = backlog_candidates.first(remaining_budget)+ leftover = remaining_budget - backlog_batch.size+ secondary_new = remaining_new.first(leftover)++ queue = primary_new.map { |event| [ event, :new ] } ++ backlog_batch.map { |event| [ event, :backfill ] } ++ secondary_new.map { |event| [ event, :new ] }++ if new_candidates.size + backlog_candidates.size > queue.size+ warnings << "detail enrichment truncated to #{queue.size} of #{new_candidates.size + backlog_candidates.size} events"+ end++ enriched_by_id = {}+ detail_backfill_count = 0details_fetched = 0- details_skipped = false- items.each do |item|- detail = nil++ queue.each do |event, kind|+ break if details_fetched >= budget++ item = event.stringify_keyscategory = item["category"].presence || EVENT_TYPE_CATEGORIES[item["eventType"].to_s]- warnings << "unsupported timeline event type #{item["eventType"]}" if category.blank?- if DETAIL_CATEGORIES.include?(category.to_s) && details_fetched < MAX_TIMELINE_DETAILS- begin- detail = normalize_event_detail(- subscribe(websocket, type: "timelineDetailV2", id: item["id"]),- item: item- )- details_fetched += 1- rescue TransientProviderError, Timeout, RateLimited- raise- rescue Error- warnings << "detail fetch failed for event #{item["id"]}"- end- elsif DETAIL_CATEGORIES.include?(category.to_s)- details_skipped = true+ next if item["id"].blank? || category.blank?+ next unless Provider::TradeRepublicTimelineEvent.importable?(item)++ details_fetched += 1+ fetched = nil+ begin+ detail = normalize_event_detail(+ subscribe(websocket, type: "timelineDetailV2", id: item["id"]),+ item: item+ )+ detail = detail&.slice(*DIVIDEND_DETAIL_KEYS) if category.to_s == DIVIDEND_DETAIL_CATEGORY+ fetched = build_normalized_event(item, category: category, detail: detail)+ rescue TransientProviderError, Timeout, RateLimited+ raise+ rescue Error+ warnings << "detail fetch failed for event #{item["id"]}"end- amount = item.dig("amount", "value")- event_detail = {- "amount" => amount,- "signed_amount" => amount,- "currency" => item.dig("amount", "currency")- }.compact- detail ||= {}- detail = event_detail.merge(detail) if event_detail.present?- events << item.slice("id", "timestamp", "title", "subtitle", "eventType")- .merge("category" => category, "detail" => detail.presence)++ if kind == :backfill+ result = fetched ? prefer_richer_event(item, fetched) : item+ detail_backfill_count += 1 if detail_backfill_improved?(item, result)+ fetched = with_price_backfill_attempt(result) if self.class.trade_detail_missing_price?(result)+ end+ enriched_by_id[item["id"].to_s] = fetched if fetched+ end++ merged_events = events.map do |event|+ id = event["id"].to_s+ enriched = enriched_by_id.delete(id)+ enriched ? prefer_richer_event(event, enriched) : eventend- newest_event_id = nil if details_skipped || events.any? { |event| DETAIL_CATEGORIES.include?(event["category"]) && event["detail"].nil? }- [ events, newest_event_id, warnings ]+ # Backfilled stored events that were not on this sync's timeline pages.+ merged_events = merge_enriched_events(merged_events, enriched_by_id.values)++ [ merged_events, warnings, detail_backfill_count ]+ end++ def detail_backfill_improved?(before, after)+ return self.class.trade_detail_complete?(after) if self.class.incomplete_trade_detail_event?(before)++ self.class.trade_detail_missing_price?(before) && !self.class.trade_detail_missing_price?(after)+ end++ def with_price_backfill_attempt(event)+ event = event.stringify_keys+ detail = (event["detail"] || {}).stringify_keys+ event.merge("detail" => detail.merge(PRICE_BACKFILL_ATTEMPTED_AT_KEY => Time.current.iso8601))+ end++ # Test/helper wrapper: enrich a raw timeline page without touching the list cursor.+ def resolve_details(websocket, items, newest_event_id, warnings)+ events = Array(items).map { |item| build_skeleton_event(item, warnings: warnings) }+ enriched, detail_warnings, = enrich_timeline_details(websocket, events, enrich_events: [])+ [ enriched, newest_event_id, warnings.concat(detail_warnings) ]+ end++ def merge_enriched_events(events, enriched_events)+ by_id = {}+ (Array(events) + Array(enriched_events)).each do |event|+ next unless event.is_a?(Hash)++ key = event["id"].presence || event+ by_id[key] = prefer_richer_event(by_id[key], event)+ end+ by_id.values+ end++ def prefer_richer_event(previous, incoming)+ return incoming if previous.blank?+ return previous if incoming.blank?++ previous = previous.stringify_keys+ incoming = incoming.stringify_keys+ merged = previous.merge(incoming)+ merged["category"] = incoming["category"].presence || previous["category"]+ merged["detail"] = prefer_richer_detail(previous["detail"], incoming["detail"])+ Provider::TradeRepublicTimelineEvent.merge_lifecycle_fields!(merged, previous, incoming)+ # compact drops nil only; boolean false for deleted/hidden must survive.+ merged.compact+ end++ def prefer_richer_detail(previous, incoming)+ previous = previous.is_a?(Hash) ? previous.stringify_keys : {}+ incoming = incoming.is_a?(Hash) ? incoming.stringify_keys : {}+ return previous.presence if incoming.blank?+ return incoming.presence if previous.blank?++ previous.merge(incoming) { |_key, old_value, new_value| new_value.presence || old_value }.presence+ end++ def build_normalized_event(item, category:, detail:)+ item = item.stringify_keys+ amount = item.dig("amount", "value")+ event_detail = {+ "amount" => amount,+ "signed_amount" => amount,+ "currency" => item.dig("amount", "currency")+ }.compact+ detail ||= {}+ detail = event_detail.merge(detail) if event_detail.present?+ event = item.slice("id", "timestamp", "title", "subtitle", "eventType")+ .merge("category" => category, "detail" => detail.presence)++ Provider::TradeRepublicTimelineEvent::LIFECYCLE_KEYS.each do |key|+ next unless item.key?(key)+ next if key == "badge" && item[key].blank?++ event[key] = item[key]+ end++ eventenddef normalize_event_detail(raw, item: nil)rows = collect_sections(raw).flat_map { |section| Array(section["data"]) }.select { |row| row.is_a?(Hash) }- shares = find_row(rows, [ "aktien", "anteile", "shares", "aktien hinzugefügt", "shares added", "aktien erhalten", "shares received", "aktien entfernt", "shares removed", "aktien gesendet", "shares sent" ])- total = find_row(rows, [ "gesamt", "total" ])+ 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)title = shares&.dig("title").to_s.downcasequantity = -quantity.abs if title.include?("entfernt") || title.include?("removed") || title.include?("gesendet") || title.include?("sent")- quantity = -quantity.abs if quantity && item&.dig("subtitle").to_s.downcase.include?("sell")+ subtitle = item&.dig("subtitle").to_s.downcase+ quantity = -quantity.abs if quantity && SELL_SUBTITLE_MARKERS.any? { |marker| subtitle.include?(marker) }amount = decimal_from_row(total)+ fee_amount = decimal_from_row(fees)+ tax_amount = decimal_from_row(taxes)+ price = decimal_from_row(price_row)+ dividend_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,+ # sell total = gross - fees/taxes. Recover share price accordingly.+ # Quantity is already signed negative for sells (subtitle/title markers).+ deductions = fee_amount.to_d.abs + tax_amount.to_d.abs+ gross = quantity.negative? ? amount.abs + deductions : amount.abs - deductions+ price = gross / quantity.abs if gross.positive?+ endreturn nil if quantity.nil? && amount.nil?- { "isin" => find_isin(item) || find_isin(raw), "name" => item&.dig("title") || find_asset_name(raw), "quantity" => decimal_string(quantity), "price" => nil, "amount" => decimal_string(amount&.abs), "currency" => currency_from_row(total) || currency_from_row(shares), "fees" => decimal_string(decimal_from_row(fees)), "taxes" => decimal_string(decimal_from_row(taxes)) }.compact++ {+ "isin" => find_isin(item) || find_isin(raw) || find_logo_isin(raw),+ "name" => item&.dig("title") || find_asset_name(raw),+ "quantity" => decimal_string(quantity),+ "price" => decimal_string(price),+ "amount" => decimal_string(amount&.abs),+ "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)+ }.compactenddef collect_sections(node, result = [])@@ -813,8 +1374,21 @@ class Provider::TradeRepublicClientdef decimal_from_row(row)text = row&.dig("detail", "text") || row&.dig("detail", "value", "text")return nil if text.blank?+normalized = text.to_s.gsub(/[^\d,.-]/, "")- normalized = normalized.gsub(".", "").tr(",", ".") if normalized.count(",") == 1 && normalized.rindex(",") > normalized.rindex(".")+ return nil if normalized.blank?++ # European: 1.024,92 or 511,96 → strip thousand dots, comma as decimal.+ # English: 1,024.92 → strip thousand commas. Leave plain 511.96 alone.+ if normalized.count(",") == 1 && (dot = normalized.rindex(".")) && normalized.rindex(",") > dot+ normalized = normalized.gsub(".", "").tr(",", ".")+ elsif normalized.count(",") == 1 && normalized.rindex(".").nil?+ normalized = normalized.tr(",", ".")+ elsif normalized.count(",") >= 1 && normalized.count(".") == 1 &&+ normalized.rindex(",") < normalized.rindex(".")+ normalized = normalized.gsub(",", "")+ end+BigDecimal(normalized)rescue ArgumentErrornil@@ -841,6 +1415,16 @@ class Provider::TradeRepublicClientvalues.firstend+ # Dividend details carry the ISIN only in the header logo path, e.g.+ # "logos/DE000A0F5UH1/v2".+ def find_logo_isin(raw)+ isin = nil+ walk(raw) do |value|+ isin ||= value[%r{\Alogos/([A-Z]{2}[A-Z0-9]{9}\d)/}, 1] if value.is_a?(String)+ end+ isin+ end+def find_asset_name(raw)rows = collect_sections(raw).flat_map { |section| Array(section["data"]) }row = rows.find { |candidate| %w[wertpapier asset vermögenswert security].include?(candidate["title"].to_s.downcase) }diff --git a/app/models/provider/trade_republic_timeline_event.rb b/app/models/provider/trade_republic_timeline_event.rbnew file mode 100644index 0000000000..193c1c5ac3--- /dev/null+++ b/app/models/provider/trade_republic_timeline_event.rb@@ -0,0 +1,218 @@+# Classification of normalized Trade Republic timeline events. The client uses+# it for detail budgeting and warnings, the account processors for import+# rules. It lives on the provider side and depends on nothing else, so the+# provider boundary stays one-way.+module Provider::TradeRepublicTimelineEvent+ CATEGORY_ORDER_EXECUTION = "orderExecution"+ CATEGORY_DEPOSIT = "PAYMENT_RECEIVED"+ CATEGORY_WITHDRAWAL = "POC_CREATED"+ CATEGORY_INTEREST = "INTEREST_PAYOUT_CREATED"+ CATEGORY_DIVIDEND = "DIVIDEND"+ KNOWN_ACTIVITY_CATEGORIES = [+ CATEGORY_DEPOSIT, CATEGORY_WITHDRAWAL, CATEGORY_INTEREST, CATEGORY_DIVIDEND, CATEGORY_ORDER_EXECUTION+ ].freeze++ EVENT_TYPE_CATEGORIES = {+ "TRADING_TRADE_EXECUTED" => "orderExecution",+ "TRADE_INVOICE" => "orderExecution",+ "ORDER_EXECUTED" => "orderExecution",+ "CRYPTO_INVOICE" => "orderExecution",+ "SAVINGS_PLAN_EXECUTED" => "orderExecution",+ "TRADING_SAVINGSPLAN_EXECUTED" => "orderExecution",+ # Savings-plan executions between mid-2024 and early 2025 arrive only as+ # invoices; Trade Republic switched to TRADING_SAVINGSPLAN_EXECUTED later.+ # Treat them as order executions so timelineDetailV2 is fetched and the+ # portfolio can import a trade.+ "SAVINGS_PLAN_INVOICE_CREATED" => "orderExecution",+ "PRIVATE_MARKET_FUND_TRADE_EXECUTED" => "orderExecution",+ "IPO_TRADE_EXECUTED" => "orderExecution",+ "BANK_TRANSACTION_INCOMING" => "PAYMENT_RECEIVED",+ "INCOMING_TRANSFER" => "PAYMENT_RECEIVED",+ "INCOMING_TRANSFER_DELEGATION" => "PAYMENT_RECEIVED",+ "PAYMENT_INBOUND" => "PAYMENT_RECEIVED",+ "PAYMENT_INBOUND_SEPA_DIRECT_DEBIT" => "PAYMENT_RECEIVED",+ "PAYMENT_INBOUND_APPLE_PAY" => "PAYMENT_RECEIVED",+ "PAYMENT_INBOUND_GOOGLE_PAY" => "PAYMENT_RECEIVED",+ "BANK_TRANSACTION_OUTGOING" => "POC_CREATED",+ "BANK_TRANSACTION_OUTGOING_DIRECT_DEBIT" => "POC_CREATED",+ "OUTGOING_TRANSFER" => "POC_CREATED",+ "OUTGOING_TRANSFER_DELEGATION" => "POC_CREATED",+ "PAYMENT_OUTBOUND" => "POC_CREATED",+ "CARD_TRANSACTION" => "POC_CREATED",+ "card_successful_transaction" => "POC_CREATED",+ # Trade Republic currently uses CARD_CASH_BACK for some card purchases+ # (for example, Marktkauf), not only for actual cashback credits. The+ # signed provider amount confirms these are cash outflows.+ "CARD_CASH_BACK" => "POC_CREATED",+ "card_refund" => "PAYMENT_RECEIVED",+ "CARD_REFUND" => "PAYMENT_RECEIVED",+ "SPARE_CHANGE_AGGREGATE" => "POC_CREATED",+ "SAVEBACK_AGGREGATE" => "POC_CREATED",+ "BANK_TRANSACTION_OUTGOING_SCHEDULED" => "POC_CREATED",+ "CARD_ATM_WITHDRAWAL" => "POC_CREATED",+ "SSP_CORPORATE_ACTION_CASH" => "DIVIDEND",+ "ssp_corporate_action_invoice_cash" => "DIVIDEND",+ "SSP_CORPORATE_ACTION_CASH_NON_DIVIDEND" => "PAYMENT_RECEIVED",+ "DIVIDEND" => "DIVIDEND",+ "CREDIT" => "DIVIDEND",+ "INTEREST_PAYOUT" => "INTEREST_PAYOUT_CREATED",+ "INTEREST_PAYOUT_CREATED" => "INTEREST_PAYOUT_CREATED",+ "TAX_REFUND" => "PAYMENT_RECEIVED",+ "ssp_tax_correction_invoice" => "PAYMENT_RECEIVED",+ "SSP_TAX_CORRECTION" => "PAYMENT_RECEIVED",+ "CARD_ORDER_FEE" => "POC_CREATED"+ }.freeze++ # Administrative / non-financial timelineActivityLog rows. These stay in the+ # stored payload for audit but must not import, warn, or inflate unknown counts.+ IGNORED_EVENT_TYPES = %w[+ ADDRESS_CHANGED+ PIN_CHANGED+ EMAIL_VALIDATED+ DEVICE_RESET+ CUSTOMER_CREATED+ SECURITIES_ACCOUNT_CREATED+ REFERENCE_ACCOUNT_CHANGED+ PUK_CREATED+ DOCUMENTS_ACCEPTED+ DOCUMENTS_CREATED+ EX_POST_COST_REPORT_CREATED+ TAX_YEAR_END_REPORT_CREATED+ QUARTERLY_REPORT+ QUARTERLY_NET_WORTH_STATEMENT_CREATED+ CARD_VERIFICATION+ ORDER_CANCELED+ ORDER_REJECTED+ TRADING_ORDER_CREATED+ TRADING_ORDER_CANCELLED+ TRADING_ORDER_REJECTED+ SSP_CORPORATE_ACTION_INFORMATIVE+ SSP_CORPORATE_ACTION_ACTIVITY+ SSP_CORPORATE_ACTION_INSTRUCTION+ SSP_CORPORATE_ACTION_UPCOMING+ CSX_CHAT_ACTIVITY+ GENERAL_MEETING+ STOCK_PERK_REFUNDED+ PRIVATE_MARKETS_SUITABILITY_QUIZ_COMPLETED+ TRADING_SAVINGSPLAN_EXECUTION_FAILED+ ].freeze++ # Timeline rows that omit eventType/category but are clearly administrative.+ # Titles are compared case-insensitively after strip.+ IGNORED_TITLES = [+ "legal documents"+ ].freeze++ NON_IMPORTABLE_STATUSES = %w[+ DECLINED+ REJECTED+ CANCELLED+ CANCELED+ FAILED+ ERROR+ ].freeze++ DECLINED_SUBTITLE_PATTERN = /declin|failed|reject|cancel/i+ LIFECYCLE_KEYS = %w[status deleted hidden badge].freeze++ class << self+ # Returns :financial, :ignored, or :unknown.+ def classify(event)+ return :unknown unless event.is_a?(Hash)++ event = event.with_indifferent_access+ event_type = event[:eventType].to_s+ return :ignored if IGNORED_EVENT_TYPES.include?(event_type)+ return :ignored if ignored_title?(event)++ return :financial if KNOWN_ACTIVITY_CATEGORIES.include?(resolved_category(event))++ :unknown+ end++ def importable?(event)+ return false unless event.is_a?(Hash)+ return false unless classify(event) == :financial+ return false if lifecycle_blocks_import?(event)++ true+ end++ # Explicit signals plus the free-text subtitle heuristic. Blocks import+ # only; destructive reconciliation must use `explicit_lifecycle_block?`.+ def lifecycle_blocks_import?(event)+ return false unless event.is_a?(Hash)+ return true if explicit_lifecycle_block?(event)++ event = event.with_indifferent_access+ event[:status].to_s.blank? && declined_subtitle?(event)+ end++ # Deleted, hidden, or a terminal non-importable status from Trade Republic.+ def explicit_lifecycle_block?(event)+ return false unless event.is_a?(Hash)++ event = event.with_indifferent_access+ return true if truthy_flag?(event[:deleted])+ return true if truthy_flag?(event[:hidden])++ NON_IMPORTABLE_STATUSES.include?(event[:status].to_s.upcase)+ end++ def non_importable_reason(event)+ return nil unless event.is_a?(Hash)++ event = event.with_indifferent_access+ return "deleted" if truthy_flag?(event[:deleted])+ return "hidden" if truthy_flag?(event[:hidden])++ status = event[:status].to_s.upcase+ return "status:#{status.downcase}" if NON_IMPORTABLE_STATUSES.include?(status)+ return "subtitle" if status.blank? && declined_subtitle?(event)+ return "ignored" if classify(event) == :ignored+ return "unknown" if classify(event) == :unknown++ nil+ end++ def resolved_category(event)+ event = event.with_indifferent_access+ event[:category].to_s.presence || EVENT_TYPE_CATEGORIES[event[:eventType].to_s]+ end++ def merge_lifecycle_fields!(merged, previous, incoming)+ previous = previous.stringify_keys+ incoming = incoming.stringify_keys++ LIFECYCLE_KEYS.each do |key|+ if incoming.key?(key)+ merged[key] = incoming[key]+ elsif previous.key?(key)+ merged[key] = previous[key]+ end+ end++ merged+ end++ private++ def ignored_title?(event)+ title = event[:title].to_s.strip.downcase+ title.present? && IGNORED_TITLES.include?(title)+ end++ def truthy_flag?(value)+ ActiveModel::Type::Boolean.new.cast(value)+ end++ # Only subtitle/badge — never title. Titles are often security or+ # merchant names and can contain substrings like "cancel" without+ # meaning the event itself failed.+ def declined_subtitle?(event)+ [ event[:subtitle], event[:badge] ].compact.any? do |value|+ value.to_s.match?(DECLINED_SUBTITLE_PATTERN)+ end+ end+ end+enddiff --git a/app/models/trade_republic_account/activities_processor.rb b/app/models/trade_republic_account/activities_processor.rbindex 9514a028ec..aa4d29c038 100644--- a/app/models/trade_republic_account/activities_processor.rb+++ b/app/models/trade_republic_account/activities_processor.rb@@ -1,12 +1,14 @@class TradeRepublicAccount::ActivitiesProcessorinclude TradeRepublicAccount::DataHelpers- # Timeline event categories that carry trade payloads once their detail has- # been resolved by the Trade Republic client boundary.- CATEGORY_ORDER_EXECUTION = "orderExecution"+ SAVEBACK_EVENT_TYPE = "SAVEBACK_AGGREGATE"+ ROUND_UP_EVENT_TYPE = "SPARE_CHANGE_AGGREGATE"+ SAVINGS_PLAN_INVOICE_EVENT_TYPE = "SAVINGS_PLAN_INVOICE_CREATED"+ SAVINGS_PLAN_EXECUTION_EVENT_TYPES = %w[TRADING_SAVINGSPLAN_EXECUTED SAVINGS_PLAN_EXECUTED].freeze- def initialize(trade_republic_account)+ def initialize(trade_republic_account, exchange_securities: {})@trade_republic_account = trade_republic_account+ @exchange_securities = exchange_securitiesenddef process@@ -14,21 +16,32 @@ class TradeRepublicAccount::ActivitiesProcessortrade_count = 0transaction_count = 0- split_accounts = linked_cash_account_present?Array(@trade_republic_account.raw_timeline_payload).each do |event|next unless event.is_a?(Hash)- next if split_accounts && @trade_republic_account.portfolio? && event.with_indifferent_access[:category].to_s != CATEGORY_ORDER_EXECUTION- next if @trade_republic_account.cash? && event.with_indifferent_access[:category].to_s == CATEGORY_ORDER_EXECUTION+ event = event.with_indifferent_access+ classification = classify_timeline_event(event)+ next if classification == :ignored+ next if lifecycle_blocks_import?(event)+ # After routing, so split portfolio/cash connections log an unknown+ # event once (from the cash side) instead of twice.+ next unless processable_event?(event)- case process_event(event.with_indifferent_access)+ if classification == :unknown+ record_unknown_event(event)+ next+ end++ case process_event(event)when :trade then trade_count += 1when :transaction then transaction_count += 1endendreconcile_split_portfolio_transactions!+ reconcile_stale_saveback_cash_transactions!+ reconcile_non_importable_entries!{ trades: trade_count, transactions: transaction_count }end@@ -55,6 +68,23 @@ class TradeRepublicAccount::ActivitiesProcessor@trade_republic_account.currencyend+ # 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+ # plus cash outflow when both accounts are linked.+ def processable_event?(event)+ event_type = event[:eventType].to_s++ return @trade_republic_account.portfolio? if saveback_event?(event_type)+ return true if round_up_event?(event_type)++ category = event[:category].to_s+ return category == CATEGORY_ORDER_EXECUTION if linked_cash_account_present? && @trade_republic_account.portfolio?+ return category != CATEGORY_ORDER_EXECUTION if @trade_republic_account.cash?++ true+ end+# Events arrive bridge-normalized:# { id:, timestamp:, category:, title:, subtitle:,# detail: { isin, name, quantity (signed), amount (magnitude),@@ -69,9 +99,15 @@ class TradeRepublicAccount::ActivitiesProcessorreturn nil unless datedetail = event[:detail] || {}+ event_type = event[:eventType].to_s++ return process_saveback(event, detail, external_id, date) if saveback_event?(event_type)+ return process_round_up(event, detail, external_id, date) if round_up_event?(event_type)case event_category(event)when CATEGORY_ORDER_EXECUTION+ return nil if duplicate_savings_plan_invoice?(event, detail, date)+import_order_execution(event, detail, external_id, date) ? :trade : nilwhen CATEGORY_DEPOSITimport_cash_movement(event, detail, external_id, date, label: cash_label(event, default: t("contribution")), sign: -1) ? :transaction : nil@@ -81,9 +117,6 @@ class TradeRepublicAccount::ActivitiesProcessorimport_cash_movement(event, detail, external_id, date, label: t("interest"), sign: -1) ? :transaction : nilwhen CATEGORY_DIVIDENDimport_cash_movement(event, detail, external_id, date, label: t("dividend"), sign: -1) ? :transaction : nil- else- record_unknown_event(event)- nilendrescue => eDebugLogEntry.capture(@@ -98,29 +131,111 @@ class TradeRepublicAccount::ActivitiesProcessornilend+ def process_saveback(event, detail, external_id, date)+ return nil unless @trade_republic_account.portfolio?++ import_order_execution(event, detail, external_id, date) ? :trade : nil+ end++ def process_round_up(event, detail, external_id, date)+ if @trade_republic_account.portfolio?+ import_order_execution(event, detail, external_id, date) ? :trade : nil+ else+ import_cash_movement(event, detail, external_id, date, label: t("round_up"), sign: 1) ? :transaction : nil+ end+ end++ # Trade Republic switched savings-plan executions from invoices to+ # TRADING_SAVINGSPLAN_EXECUTED. Should an execution ever arrive in both+ # shapes, import only the execution.+ def duplicate_savings_plan_invoice?(event, detail, date)+ return false unless event[:eventType].to_s == SAVINGS_PLAN_INVOICE_EVENT_TYPE++ key = savings_plan_key(detail, date)+ return false unless savings_plan_execution_keys.include?(key)++ DebugLogEntry.capture(+ category: "sync",+ level: "info",+ message: "Skipped Trade Republic savings-plan invoice duplicated by an execution event",+ source: "trade_republic",+ family: @trade_republic_account.trade_republic_item.family,+ provider_key: "trade_republic",+ account: account,+ metadata: { event_id: event[:id], isin: key[0], date: key[1], quantity: key[2]&.to_s("F") }+ )+ true+ end++ def savings_plan_execution_keys+ @savings_plan_execution_keys ||= Array(@trade_republic_account.raw_timeline_payload).each_with_object(Set.new) do |event, keys|+ next unless event.is_a?(Hash)++ event = event.with_indifferent_access+ next unless SAVINGS_PLAN_EXECUTION_EVENT_TYPES.include?(event[:eventType].to_s)+ next unless importable_timeline_event?(event)++ keys << savings_plan_key(event[:detail] || {}, parse_date(event[:timestamp]))+ end+ end++ def savings_plan_key(detail, date)+ [ detail[:isin].to_s, date, parse_decimal(detail[:quantity])&.abs ]+ end++ def saveback_event?(event_type)+ event_type == SAVEBACK_EVENT_TYPE+ end++ def round_up_event?(event_type)+ event_type == ROUND_UP_EVENT_TYPE+ end+def import_order_execution(event, detail, external_id, date)isin = detail[:isin].to_squantity = parse_decimal(detail[:quantity])return false if isin.blank? || quantity.nil? || quantity.zero?- security = resolve_security(isin, detail[:name] || event[:title])+ security = resolve_security(+ isin,+ detail[:name] || event[:title],+ symbol: detail[:symbol],+ exchange_slug: detail[:exchange_slug]+ )return false unless securityis_buy = quantity.positive?signed_quantity = quantity # Bridge reports sells as negative quantities already- # Amount falls back to |quantity| × price only when the provider omits- # the exact cash amount. Fees and taxes stay embedded in the provider- # amount rather than being inferred separately.+ fee = parse_decimal(detail[:fees])&.abs+ fee = nil if fee&.zero?+ tax = parse_decimal(detail[:taxes])&.abs+ tax = nil if tax&.zero?+ # Match the client detail parser: cash totals embed fees and taxes.+ costs = (fee || 0) + (tax || 0)++ # Prefer the provider share price. Fall back to cash amount net of costs+ # so the per-share price is not inflated by transaction costs.price = parse_decimal(detail[:price])price = nil if price&.zero?amount = parse_decimal(detail[:amount])- amount = quantity.abs * price.abs if (!amount || amount.zero?) && price+ if (!amount || amount.zero?) && price+ gross = quantity.abs * price.abs+ # Costs increase buy cost and reduce sell proceeds (same as SnapTrade /+ # manual trades).+ amount = is_buy ? gross + costs : gross - costs+ endreturn false unless amount && !amount.zero?signed_amount = is_buy ? -amount.abs : amount.abs- price ||= amount.abs / signed_quantity.abs+ if price.nil?+ # Provider totals include costs: buy total = gross + costs, sell total =+ # gross - costs. Recover share price from the cash amount accordingly.+ gross = is_buy ? amount.abs - costs : amount.abs + costs+ price = gross / signed_quantity.abs if gross.positive?+ price ||= amount.abs / signed_quantity.abs+ endentry = import_adapter.import_trade(external_id: external_id,@@ -128,9 +243,10 @@ class TradeRepublicAccount::ActivitiesProcessorquantity: signed_quantity,price: price,amount: signed_amount,+ fee: fee,currency: detail[:currency].presence || currency,date: date,- name: build_trade_name(security.ticker, signed_quantity),+ name: build_trade_name(detail[:name], security, signed_quantity),source: "trade_republic",activity_label: is_buy ? "Buy" : "Sell")@@ -181,7 +297,9 @@ class TradeRepublicAccount::ActivitiesProcessorevent_type: event[:eventType],title: event[:title],subtitle: event[:subtitle],- provider_detail: detail.except(:amount, :signed_amount, :currency)+ provider_detail: detail.except(+ :amount, :signed_amount, :currency, *Provider::TradeRepublicClient::RETRY_MARKER_KEYS+ )}.compact})@@ -205,7 +323,8 @@ class TradeRepublicAccount::ActivitiesProcessorsigned_amount = parse_decimal(event.dig(:detail, :signed_amount) || event.dig(:detail, :amount))return CATEGORY_WITHDRAWAL if event[:eventType].to_s == "CARD_CASH_BACK" && signed_amount&.negative?- event[:category].to_s+ event[:category].to_s.presence ||+ Provider::TradeRepublicClient::EVENT_TYPE_CATEGORIES[event[:eventType].to_s].to_senddef cash_label(event, default:)@@ -222,6 +341,8 @@ class TradeRepublicAccount::ActivitiesProcessort("card_refund")when "TAX_REFUND", "SSP_TAX_CORRECTION", "ssp_tax_correction_invoice"t("tax_refund")+ when ROUND_UP_EVENT_TYPE+ t("round_up")elsedefaultend@@ -256,6 +377,199 @@ class TradeRepublicAccount::ActivitiesProcessor)end+ # Saveback used to import as a cash withdrawal. Once split accounts are+ # linked, remove those leftover cash entries only after the portfolio+ # replacement trade exists, and unless the user edited or split them.+ def reconcile_stale_saveback_cash_transactions!+ return unless @trade_republic_account.cash?++ portfolio_account = linked_portfolio_account+ return unless portfolio_account++ saveback_event_ids = Array(@trade_republic_account.raw_timeline_payload).filter_map do |event|+ next unless event.is_a?(Hash)+ next unless event["eventType"].to_s == SAVEBACK_EVENT_TYPE++ event["id"].presence+ end+ return if saveback_event_ids.empty?++ external_ids = saveback_event_ids.map { |event_id| "trade_republic_event_#{event_id}" }+ candidates = account.entries+ .where(source: "trade_republic", entryable_type: "Transaction")+ .where(external_id: external_ids)+ .includes(:entryable)++ removed_count = 0+ skipped_count = 0++ candidates.find_each do |entry|+ event_type = entry.entryable.try(:extra)&.dig("trade_republic", "event_type")+ next if event_type.present? && event_type != SAVEBACK_EVENT_TYPE++ if entry.protected_from_sync? || entry.split_parent? || entry.split_child?+ skipped_count += 1+ DebugLogEntry.capture(+ category: "sync",+ level: "info",+ message: "Skipped removing protected Saveback cash transaction #{entry.external_id}",+ source: "trade_republic",+ family: @trade_republic_account.trade_republic_item.family,+ provider_key: "trade_republic",+ account: account,+ metadata: {+ trade_republic_account_id: @trade_republic_account.id,+ external_id: entry.external_id,+ protection_reason: entry.protection_reason || (entry.split_parent? || entry.split_child? ? :split : nil)+ }+ )+ next+ end++ # Keep the legacy cash row until the portfolio trade is present so an+ # incomplete Saveback detail cannot open a ledger gap.+ unless portfolio_saveback_trade_present?(portfolio_account, entry.external_id)+ skipped_count += 1+ DebugLogEntry.capture(+ category: "sync",+ level: "info",+ message: "Skipped removing Saveback cash transaction #{entry.external_id} until portfolio trade exists",+ source: "trade_republic",+ family: @trade_republic_account.trade_republic_item.family,+ provider_key: "trade_republic",+ account: account,+ metadata: {+ trade_republic_account_id: @trade_republic_account.id,+ external_id: entry.external_id,+ portfolio_account_id: portfolio_account.id+ }+ )+ next+ end++ entry.destroy!+ removed_count += 1+ end++ return unless removed_count.positive? || skipped_count.positive?++ DebugLogEntry.capture(+ category: "sync",+ level: "info",+ message: "Reconciled stale Saveback cash transactions (removed=#{removed_count}, skipped=#{skipped_count})",+ source: "trade_republic",+ family: @trade_republic_account.trade_republic_item.family,+ provider_key: "trade_republic",+ account: account,+ metadata: {+ trade_republic_account_id: @trade_republic_account.id,+ removed_count: removed_count,+ skipped_count: skipped_count+ }+ )+ end++ def linked_portfolio_account+ portfolio_tr = @trade_republic_account.trade_republic_item.trade_republic_accounts.find_by(kind: "portfolio")+ return unless portfolio_tr++ portfolio_account = portfolio_tr.current_account+ return unless portfolio_account+ return if portfolio_account.pending_deletion? || portfolio_account.disabled?++ portfolio_account+ end++ def portfolio_saveback_trade_present?(portfolio_account, external_id)+ portfolio_account.entries+ .where(source: "trade_republic", entryable_type: "Trade", external_id: external_id)+ .exists?+ end++ # Remove previously imported entries whose upstream events are now deleted,+ # hidden or in a terminal non-importable status, unless the user protected+ # them. Events blocked only by the free-text subtitle heuristic are skipped+ # on import but never delete existing entries.+ def reconcile_non_importable_entries!+ explicit_ids = []+ heuristic_ids = []+ Array(@trade_republic_account.raw_timeline_payload).each do |event|+ next unless event.is_a?(Hash)+ next unless lifecycle_blocks_import?(event)++ event_id = event["id"].presence || event[:id].presence+ next if event_id.blank?++ (explicit_lifecycle_block?(event) ? explicit_ids : heuristic_ids) << "trade_republic_event_#{event_id}"+ end+ return if explicit_ids.empty? && heuristic_ids.empty?++ candidates = account.entries+ .where(source: "trade_republic")+ .where(external_id: explicit_ids + heuristic_ids)+ .includes(:entryable)++ removed_count = 0+ skipped_count = 0+ heuristic_ids = heuristic_ids.to_set++ candidates.find_each do |entry|+ if heuristic_ids.include?(entry.external_id)+ skipped_count += 1+ DebugLogEntry.capture(+ category: "sync",+ level: "info",+ message: "Kept Trade Republic entry #{entry.external_id} flagged only by its subtitle",+ source: "trade_republic",+ family: @trade_republic_account.trade_republic_item.family,+ provider_key: "trade_republic",+ account: account,+ metadata: { trade_republic_account_id: @trade_republic_account.id, external_id: entry.external_id }+ )+ next+ end++ if entry.protected_from_sync? || entry.split_parent? || entry.split_child?+ skipped_count += 1+ DebugLogEntry.capture(+ category: "sync",+ level: "info",+ message: "Skipped removing protected Trade Republic entry for non-importable event #{entry.external_id}",+ source: "trade_republic",+ family: @trade_republic_account.trade_republic_item.family,+ provider_key: "trade_republic",+ account: account,+ metadata: {+ trade_republic_account_id: @trade_republic_account.id,+ external_id: entry.external_id,+ protection_reason: entry.protection_reason || (entry.split_parent? || entry.split_child? ? :split : nil)+ }+ )+ next+ end++ entry.destroy!+ removed_count += 1+ end++ return unless removed_count.positive? || skipped_count.positive?++ DebugLogEntry.capture(+ category: "sync",+ level: "info",+ message: "Reconciled non-importable Trade Republic entries (removed=#{removed_count}, skipped=#{skipped_count})",+ source: "trade_republic",+ family: @trade_republic_account.trade_republic_item.family,+ provider_key: "trade_republic",+ account: account,+ metadata: {+ trade_republic_account_id: @trade_republic_account.id,+ removed_count: removed_count,+ skipped_count: skipped_count+ }+ )+ end+def linked_cash_account_present?@trade_republic_account.trade_republic_item.trade_republic_accounts.where(kind: "cash")@@ -271,12 +585,20 @@ class TradeRepublicAccount::ActivitiesProcessorsource: "trade_republic",family: @trade_republic_account.trade_republic_item.family,provider_key: "trade_republic",- metadata: { event_id: event[:id], category: event[:category] }+ metadata: {+ event_id: event[:id],+ event_type: event[:eventType],+ category: event[:category],+ status: event[:status]+ })end- def build_trade_name(ticker, signed_quantity)- action = signed_quantity.negative? ? t("sell") : t("buy")- "#{action} #{signed_quantity.abs} shares of #{ticker}"+ def build_trade_name(provider_name, security, signed_quantity)+ name = provider_name.presence || security.name.presence || security.ticker+ quantity = signed_quantity.abs.to_s("F").sub(/\.0+\z/, "")+ return "#{security.ticker} · #{quantity}x" if name.casecmp?(security.ticker)++ "#{security.ticker} · #{quantity}x #{name}"endenddiff --git a/app/models/trade_republic_account/data_helpers.rb b/app/models/trade_republic_account/data_helpers.rbindex bf427c8109..685ce76f9b 100644--- a/app/models/trade_republic_account/data_helpers.rb+++ b/app/models/trade_republic_account/data_helpers.rb@@ -1,22 +1,65 @@module TradeRepublicAccount::DataHelpersextend ActiveSupport::Concern- # Timeline event categories Trade Republic emits. Only explicitly mapped- # categories are imported; anything unknown is skipped and recorded rather- # than guessed into a transaction.- CATEGORY_DEPOSIT = "PAYMENT_RECEIVED"- CATEGORY_WITHDRAWAL = "POC_CREATED"- CATEGORY_INTEREST = "INTEREST_PAYOUT_CREATED"- CATEGORY_DIVIDEND = "DIVIDEND"- KNOWN_ACTIVITY_CATEGORIES = [ CATEGORY_DEPOSIT, CATEGORY_WITHDRAWAL, CATEGORY_INTEREST, CATEGORY_DIVIDEND, "orderExecution" ].freeze+ # Timeline event classification lives in Provider::TradeRepublicTimelineEvent;+ # including it exposes the CATEGORY_* constants to the processors.+ include Provider::TradeRepublicTimelineEventTRANSFER_EVENT_TYPES = %w[PAYMENT_INBOUND PAYMENT_OUTBOUND INCOMING_TRANSFER OUTGOING_TRANSFERINCOMING_TRANSFER_DELEGATION OUTGOING_TRANSFER_DELEGATION].freeze+ class << self+ # Portfolio is the full timeline; cash is a filtered subset. Prefer portfolio+ # rows, then append cash-only events, deduped by event id.+ def unique_timeline_events(portfolio_events, cash_events = [])+ seen = {}+ result = []++ (Array(portfolio_events) + Array(cash_events)).each do |event|+ next unless event.is_a?(Hash)++ key = timeline_event_key(event)+ next if seen[key]++ seen[key] = true+ result << event+ end++ result+ end++ def timeline_event_key(event)+ event = event.with_indifferent_access+ return event[:id].to_s if event[:id].present?++ [ event[:timestamp], event[:eventType], event[:title], event[:subtitle] ].map(&:to_s).join("|")+ end+ end+private+ def classify_timeline_event(event)+ Provider::TradeRepublicTimelineEvent.classify(event)+ end++ def importable_timeline_event?(event)+ Provider::TradeRepublicTimelineEvent.importable?(event)+ end++ def lifecycle_blocks_import?(event)+ Provider::TradeRepublicTimelineEvent.lifecycle_blocks_import?(event)+ end++ def explicit_lifecycle_block?(event)+ Provider::TradeRepublicTimelineEvent.explicit_lifecycle_block?(event)+ end++ def non_importable_reason(event)+ Provider::TradeRepublicTimelineEvent.non_importable_reason(event)+ end+def parse_decimal(value)return nil if value.nil?@@ -43,15 +86,296 @@ module TradeRepublicAccount::DataHelpersnilend- # Resolve (or create) a Security from a Trade Republic position. The ISIN- # is the stable provider identifier; ticker matching falls back to it- # because the securities table has no ISIN column.- def resolve_security(isin, name)+ # Trade Republic exchange slugs → ISO MICs.+ EXCHANGE_SLUG_TO_MIC = {+ "XETR" => "XETR",+ "TDG" => "TGAT",+ "LSX" => "XHAM"+ }.freeze+ OFFLINE_ISIN_REASON = "trade_republic_isin"++ # Resolve (or create) a Security from a Trade Republic position/trade.+ # Prefer an exact exchange ticker when the client supplied one; otherwise+ # keep the ISIN as ticker but mark the security offline so market-data+ # importers skip it while snapshot prices still value the holding.+ def resolve_security(isin, name, symbol: nil, exchange_slug: nil)return nil if isin.blank?- Security.find_by(ticker: isin) ||- Security.create!(ticker: isin, name: name.presence || isin)+ usable_symbol, mic = exchange_listing_for(isin, symbol: symbol, exchange_slug: exchange_slug)+ if usable_symbol+ security = cached_exchange_security(usable_symbol, mic, name)+ rematch_account_from_isin!(isin, security) if security+ return security if security+ end++ resolve_offline_isin_security(isin, name)+ end++ # [symbol, mic] when Trade Republic supplied a usable exchange ticker.+ def exchange_listing_for(isin, symbol: nil, exchange_slug: nil)+ position = position_metadata_for(isin)+ symbol = symbol.to_s.presence || position&.dig(:symbol)+ exchange_slug = exchange_slug.to_s.presence || position&.dig(:exchange_slug)+ mic = mic_for_exchange_slug(exchange_slug)+ usable_symbol = usable_exchange_symbol(symbol, isin)++ [ usable_symbol, mic ] if usable_symbol.present? && mic.present?+ end++ # Pre-resolved by TradeRepublicAccount::SecurityPrefetcher so the provider+ # search runs before Processor opens its transaction.+ def exchange_securities+ @exchange_securities ||= {}+ end++ def cached_exchange_security(symbol, mic, name)+ key = [ symbol, mic ]+ return exchange_securities[key] if exchange_securities[key]++ security = resolve_exchange_security(symbol, mic, name)+ exchange_securities[key] = security if security+ security+ end++ # Timeline trade details contain an ISIN but no exchange symbol. Reuse the+ # metadata fetched for the matching portfolio position so holdings and+ # trades resolve to the same Security.+ def position_metadata_for(isin)+ position = Array(@trade_republic_account&.raw_positions_payload).find do |candidate|+ candidate.is_a?(Hash) && candidate.with_indifferent_access[:isin].to_s == isin.to_s+ end++ position&.with_indifferent_access+ end++ def usable_exchange_symbol(symbol, isin)+ candidate = symbol.to_s.strip.presence+ return nil if candidate.blank?+ return nil if candidate.casecmp?(isin.to_s)++ candidate+ end++ def mic_for_exchange_slug(exchange_slug)+ EXCHANGE_SLUG_TO_MIC[exchange_slug.to_s.strip.upcase].presence+ end++ def resolve_exchange_security(symbol, mic, name)+ price_provider = available_price_provider++ existing = Security.find_by_ticker_and_exchange(+ ticker: symbol,+ exchange_operating_mic: mic+ )+ if existing+ ensure_price_provider!(existing, price_provider)+ return existing+ end++ confirmed = confirm_exchange_security_with_provider(symbol, mic, name, price_provider)+ return confirmed if confirmed++ find_or_create_exchange_security!(+ ticker: symbol,+ exchange_operating_mic: mic,+ name: name,+ price_provider: price_provider+ )+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique+ existing = Security.find_by_ticker_and_exchange(ticker: symbol, exchange_operating_mic: mic)+ ensure_price_provider!(existing, price_provider) if existing+ existing+ end++ # Exact ticker + MIC only — never fall through to Security::Resolver's+ # fuzzy name search, which can attach the wrong fund.+ def confirm_exchange_security_with_provider(symbol, mic, name, price_provider)+ return nil if price_provider.blank?++ match = Security.search_provider(+ symbol,+ country_code: country_code_for_mic(mic),+ exchange_operating_mic: mic+ ).find { |candidate| provider_ticker_confirms?(candidate.ticker, symbol, candidate.exchange_operating_mic, mic) }++ return nil unless match++ match_mic = match.exchange_operating_mic.presence || mic+ Security.transaction(requires_new: true) do+ security = Security.find_or_initialize_by_ticker_and_exchange(+ ticker: match.ticker,+ exchange_operating_mic: match_mic+ )+ security.name = match.name.presence || name.presence || security.name || match.ticker+ security.country_code = match.country_code.presence || country_code_for_mic(mic)+ security.price_provider = price_provider if security.price_provider.blank?+ security.save!+ security+ end+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique => e+ existing = Security.find_by_ticker_and_exchange(ticker: match.ticker, exchange_operating_mic: match_mic)+ if existing+ ensure_price_provider!(existing, price_provider)+ existing+ else+ Rails.logger.warn("TradeRepublicAccount - Provider security confirm failed for #{symbol}/#{mic}: #{e.message}")+ nil+ end+ rescue StandardError => e+ Rails.logger.warn("TradeRepublicAccount - Provider security confirm failed for #{symbol}/#{mic}: #{e.message}")+ nil+ end++ def provider_ticker_confirms?(provider_ticker, symbol, provider_mic, expected_mic)+ return false if provider_ticker.blank?++ canonical_provider = Security.canonical_exchange_operating_mic(provider_mic)+ canonical_expected = Security.canonical_exchange_operating_mic(expected_mic)+ return false if canonical_provider.blank? || canonical_expected.blank?+ return false if canonical_provider != canonical_expected++ ticker = provider_ticker.to_s.upcase+ base = symbol.to_s.upcase+ ticker == base || ticker.start_with?("#{base}.")+ end++ def available_price_provider+ Setting.enabled_securities_providers.find do |provider_key|+ Security.provider_for(provider_key).present?+ end+ end++ def find_or_create_exchange_security!(ticker:, exchange_operating_mic:, name:, price_provider:)+ Security.transaction(requires_new: true) do+ security = Security.find_or_initialize_by_ticker_and_exchange(+ ticker: ticker,+ exchange_operating_mic: exchange_operating_mic+ )+ security.name = name.presence || security.name || ticker+ security.country_code = country_code_for_mic(exchange_operating_mic)+ security.price_provider = price_provider if price_provider.present? && security.price_provider.blank?+ security.save!+ security+ end+ end++ def country_code_for_mic(mic)+ return nil if mic.blank?++ Security::EXCHANGES.dig(mic.to_s.upcase, "country")+ end++ def ensure_price_provider!(security, price_provider)+ attrs = {}+ if price_provider.present? && security.price_provider.blank?+ attrs[:price_provider] = price_provider+ end+ security.update!(attrs) if attrs.any?+ end++ # Securities are shared across families, so an existing ISIN row is reused+ # as-is: its offline state belongs to whichever flow set it.+ def resolve_offline_isin_security(isin, name)+ existing = Security.find_by(ticker: isin)+ return existing if existing++ Security.transaction(requires_new: true) do+ Security.new(+ ticker: isin,+ name: name.presence || isin,+ offline: true,+ offline_reason: OFFLINE_ISIN_REASON+ ).tap(&:save!)+ endrescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUniqueSecurity.find_by(ticker: isin)end++ # Securities are global. When an account previously stored the ISIN as the+ # ticker, move only this account's holdings and trades onto the resolved+ # exchange security instead of rewriting the shared ISIN row.+ #+ # Holdings use a unique index on (account_id, security_id, date, currency).+ # Blind update_all can raise RecordNotUnique when today's exchange holding+ # already exists (e.g. HoldingsProcessor imported it before Activities+ # rematch), which aborts the outer Processor transaction. Move row-by-row+ # and drop the stale ISIN duplicate on collision.+ def rematch_account_from_isin!(isin, to_security)+ return unless account.present? && to_security.present?++ @rematched_isins ||= Set.new+ return unless @rematched_isins.add?([ isin.to_s, to_security.id ])++ from_security = Security.find_by(ticker: isin)+ return unless from_security+ return if from_security.id == to_security.id+ return 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+ )+ end++ def rematch_holdings_from_isin!(from_security, to_security)+ existing_keys = account.holdings+ .where(security_id: to_security.id)+ .pluck(:date, :currency)+ .to_set++ account.holdings.where(security_id: from_security.id).find_each do |holding|+ key = [ holding.date, holding.currency ]+ if existing_keys.include?(key)+ existing = account.holdings.find_by!(+ security_id: to_security.id,+ date: 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.+ 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+ end+ attrs[: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+ }+ )+ end++ existing.update!(attrs) if attrs.any?+ holding.destroy!+ else+ holding.update!(+ security_id: to_security.id,+ provider_security_id: holding.provider_security_id.presence || from_security.id+ )+ existing_keys << key+ end+ end+ endenddiff --git a/app/models/trade_republic_account/holdings_processor.rb b/app/models/trade_republic_account/holdings_processor.rbindex 055d9b9fac..68a0d61b19 100644--- a/app/models/trade_republic_account/holdings_processor.rb+++ b/app/models/trade_republic_account/holdings_processor.rb@@ -1,8 +1,9 @@class TradeRepublicAccount::HoldingsProcessorinclude TradeRepublicAccount::DataHelpers- def initialize(trade_republic_account)+ def initialize(trade_republic_account, exchange_securities: {})@trade_republic_account = trade_republic_account+ @exchange_securities = exchange_securitiesenddef process@@ -39,7 +40,12 @@ class TradeRepublicAccount::HoldingsProcessorisin = position[:isin].to_sreturn if isin.blank?- security = resolve_security(isin, position[:name])+ security = resolve_security(+ isin,+ position[:name],+ symbol: position[:symbol],+ exchange_slug: position[:exchange_slug]+ )return unless securityquantity = parse_decimal(position[:quantity])diff --git a/app/models/trade_republic_account/processor.rb b/app/models/trade_republic_account/processor.rbindex 621b806bcf..fba43d2b90 100644--- a/app/models/trade_republic_account/processor.rb+++ b/app/models/trade_republic_account/processor.rb@@ -8,10 +8,12 @@ class TradeRepublicAccount::Processordef processreturn unless account.present?+ exchange_securities = TradeRepublicAccount::SecurityPrefetcher.new(trade_republic_account).prefetch+ActiveRecord::Base.transaction doupdate_account_balance!- TradeRepublicAccount::HoldingsProcessor.new(trade_republic_account).process- TradeRepublicAccount::ActivitiesProcessor.new(trade_republic_account).process+ TradeRepublicAccount::HoldingsProcessor.new(trade_republic_account, exchange_securities: exchange_securities).process+ TradeRepublicAccount::ActivitiesProcessor.new(trade_republic_account, exchange_securities: exchange_securities).processendaccount.broadcast_sync_completediff --git a/app/models/trade_republic_account/security_prefetcher.rb b/app/models/trade_republic_account/security_prefetcher.rbnew file mode 100644index 0000000000..c37b17d877--- /dev/null+++ b/app/models/trade_republic_account/security_prefetcher.rb@@ -0,0 +1,61 @@+# Resolves every exchange-listed security referenced by the stored payloads+# before TradeRepublicAccount::Processor opens its database transaction.+# Unknown listings trigger Security.search_provider (HTTP with a multi-second+# deadline); doing that inside the transaction would hold it open for the+# duration of every lookup.+class TradeRepublicAccount::SecurityPrefetcher+ include TradeRepublicAccount::DataHelpers++ def initialize(trade_republic_account)+ @trade_republic_account = trade_republic_account+ end++ # Returns { [symbol, mic] => Security } for the account processors.+ def prefetch+ listings.each do |(symbol, mic), name|+ cached_exchange_security(symbol, mic, name)+ rescue StandardError => e+ Rails.logger.warn("TradeRepublicAccount::SecurityPrefetcher - #{symbol}/#{mic}: #{e.message}")+ end++ exchange_securities+ end++ private++ def listings+ position_listings.merge(trade_listings) { |_key, position_name, _trade_name| position_name }+ end++ def position_listings+ Array(@trade_republic_account.raw_positions_payload).each_with_object({}) do |position, map|+ next unless position.is_a?(Hash)++ position = position.with_indifferent_access+ add_listing(map, position[:isin], position[:name], position[:symbol], position[:exchange_slug])+ end+ end++ def trade_listings+ return {} unless @trade_republic_account.portfolio?++ Array(@trade_republic_account.raw_timeline_payload).each_with_object({}) do |event, map|+ next unless event.is_a?(Hash)+ next unless Provider::TradeRepublicClient.requires_trade_detail?(event)+ next unless importable_timeline_event?(event)++ event = event.with_indifferent_access+ detail = event[:detail]+ next unless detail.is_a?(Hash)++ add_listing(map, detail[:isin], detail[:name] || event[:title], detail[:symbol], detail[:exchange_slug])+ end+ end++ def add_listing(map, isin, name, symbol, exchange_slug)+ return if isin.blank?++ listing = exchange_listing_for(isin.to_s, symbol: symbol, exchange_slug: exchange_slug)+ map[listing] ||= name if listing+ end+enddiff --git a/app/models/trade_republic_item.rb b/app/models/trade_republic_item.rbindex 4f8e3e6184..5b707b57c3 100644--- a/app/models/trade_republic_item.rb+++ b/app/models/trade_republic_item.rb@@ -64,7 +64,12 @@ class TradeRepublicItem < ApplicationRecorddef process_accountsreturn [] if trade_republic_accounts.empty?- linked_trade_republic_accounts.includes(account_provider: :account).each_with_object([]) do |tr_account, results|+ # Portfolio before cash so Saveback trades exist before cash reconciliation+ # removes legacy Saveback withdrawals in the same process_accounts pass.+ linked_trade_republic_accounts+ .includes(account_provider: :account)+ .order(Arel.sql("CASE kind WHEN 'portfolio' THEN 0 WHEN 'cash' THEN 1 ELSE 2 END"), :id)+ .each_with_object([]) do |tr_account, results|account = tr_account.current_accountnext unless accountnext if account.pending_deletion? || account.disabled?@@ -159,16 +164,23 @@ class TradeRepublicItem < ApplicationRecorddef data_quality_summarypositions = trade_republic_accounts.where(kind: "portfolio").flat_map { |account| Array(account.raw_positions_payload) }- events = trade_republic_accounts.flat_map { |account| Array(account.raw_timeline_payload) }- unknown_events = events.count do |event|- !event.is_a?(Hash) || !TradeRepublicAccount::DataHelpers::KNOWN_ACTIVITY_CATEGORIES.include?(event["category"])+ portfolio_events = trade_republic_accounts.where(kind: "portfolio").flat_map { |account| Array(account.raw_timeline_payload) }+ cash_events = trade_republic_accounts.where(kind: "cash").flat_map { |account| Array(account.raw_timeline_payload) }+ unique_events = TradeRepublicAccount::DataHelpers.unique_timeline_events(portfolio_events, cash_events)+ hash_positions = positions.select { |position| position.is_a?(Hash) }+ unknown_events = unique_events.count do |event|+ Provider::TradeRepublicTimelineEvent.classify(event) == :unknown+ end+ pending_trade_details = unique_events.count do |event|+ Provider::TradeRepublicClient.incomplete_trade_detail_event?(event)end{- positions: positions.size,- unpriced_positions: positions.count { |position| position["price"].blank? },- events: events.size,+ positions: hash_positions.size,+ unpriced_positions: hash_positions.count { |position| position["price"].blank? },+ events: unique_events.size,unknown_events: unknown_events,+ pending_trade_details: pending_trade_details,linked_accounts: linked_accounts_count,unlinked_accounts: unlinked_accounts_count}diff --git a/app/models/trade_republic_item/importer.rb b/app/models/trade_republic_item/importer.rbindex a24429d7ec..412f77dd4b 100644--- a/app/models/trade_republic_item/importer.rb+++ b/app/models/trade_republic_item/importer.rb@@ -18,7 +18,10 @@ class TradeRepublicItem::Importerdef importresult = provider.sync(session_txt: trade_republic_item.session_blob,- known_newest_event_id: known_newest_event_id+ known_newest_event_id: known_newest_event_id,+ enrich_events: events_needing_detail_enrichment,+ symbol_lookup_isins: isins_needing_symbol_lookup,+ known_instrument_symbols: stored_instrument_symbols)data = result.data@@ -34,14 +37,17 @@ class TradeRepublicItem::Importerupsert_account(data, domain_statuses: domain_statuses)trade_republic_item.update!(status: :good,- newest_event_id: domain_statuses["timeline"] == "success" && data["newest_event_id"].present? ? data["newest_event_id"] : trade_republic_item.newest_event_id,+ newest_event_id: timeline_cursor_for(data, domain_statuses),session_blob: data["session_txt"].presence || trade_republic_item.session_blob)endrecord_provider_warnings(data["warnings"])- { success: true }+ {+ success: true,+ detail_backfill_count: data["detail_backfill_count"].to_i+ }endprivate@@ -72,9 +78,14 @@ class TradeRepublicItem::Importercash_balance: 0,positions: Array(data["positions"]),events: data["events"],+ instrument_symbols: data["instrument_symbols"],+ unresolved_symbol_isins: data["unresolved_symbol_isins"],warnings: position_warnings(data),domain_statuses: domain_statuses)+ # Pass every event into the cash merge, including orderExecution. Filtering+ # happens after merge so a newly categorized savings-plan event can replace+ # and remove its older unmapped cash copy.upsert_kind(kind: "cash",external_id: "cash:#{account_id}",@@ -83,13 +94,14 @@ class TradeRepublicItem::Importercurrent_balance: cash_balance(data),cash_balance: cash_balance(data),positions: [],- events: Array(data["events"]).reject { |event| event["category"] == "orderExecution" },+ events: Array(data["events"]),+ instrument_symbols: data["instrument_symbols"],warnings: [],domain_statuses: domain_statuses)end- def upsert_kind(kind:, external_id:, name:, currency:, current_balance:, cash_balance:, positions:, events:, warnings:, domain_statuses:)+ def upsert_kind(kind:, external_id:, name:, currency:, current_balance:, cash_balance:, positions:, events:, instrument_symbols:, warnings:, domain_statuses:, unresolved_symbol_isins: [])tr_account = trade_republic_item.trade_republic_accounts.find_by(trade_republic_account_id: external_id) ||trade_republic_item.trade_republic_accounts.find_or_initialize_by(kind: kind)portfolio_status = domain_statuses["portfolio"]@@ -116,7 +128,13 @@ class TradeRepublicItem::Importerendif timeline_status != "failed"- attrs[:raw_timeline_payload] = merge_timeline_events(tr_account.raw_timeline_payload, events)+ merged = merge_timeline_events(tr_account.raw_timeline_payload, events)+ apply_instrument_symbols!(merged, instrument_symbols)+ stamp_symbol_lookup_attempts!(merged, unresolved_symbol_isins)+ # Drop order executions before the size cap so they never crowd out+ # cash events on the cash account.+ merged = merged.reject { |event| event_category(event) == "orderExecution" } if kind == "cash"+ attrs[:raw_timeline_payload] = merged.last(MAX_TIMELINE_EVENTS)endtr_account.assign_attributes(attrs)@@ -165,6 +183,80 @@ class TradeRepublicItem::Importertrade_republic_item.newest_event_idend+ # Incomplete trade-detail events and complete trades still missing a share+ # price (stored before execution price/fees were parsed). Oldest first so+ # repeated syncs progressively drain historical starvation.+ def events_needing_detail_enrichment+ portfolio = trade_republic_item.trade_republic_accounts.find_by(kind: "portfolio")+ return [] unless portfolio++ Array(portfolio.raw_timeline_payload)+ .select do |event|+ Provider::TradeRepublicClient.incomplete_trade_detail_event?(event) ||+ Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(event)+ end+ .sort_by { |event| event_timestamp(event) }+ .first(Provider::TradeRepublicClient::MAX_TIMELINE_DETAILS)+ end++ # Sold / historical trade ISINs that already have complete details but still+ # lack an exchange ticker. Incremental syncs stop at newest_event_id, so+ # these must be passed explicitly for instrument lookup.+ def isins_needing_symbol_lookup+ portfolio = trade_republic_item.trade_republic_accounts.find_by(kind: "portfolio")+ return [] unless portfolio++ Array(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+ end.uniq.first(Provider::TradeRepublicClient::MAX_INSTRUMENT_LOOKUPS)+ end++ # Exchange tickers stored by earlier syncs; the client skips the+ # instrument subscription for these positions.+ def stored_instrument_symbols+ portfolio = trade_republic_item.trade_republic_accounts.find_by(kind: "portfolio")+ return {} unless portfolio++ Provider::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.+ def timeline_cursor_for(data, domain_statuses)+ pagination_complete = if data.key?("timeline_pagination_complete")+ data["timeline_pagination_complete"]+ else+ domain_statuses["timeline"] == "success"+ end+ return trade_republic_item.newest_event_id unless pagination_complete+ return trade_republic_item.newest_event_id if data["newest_event_id"].blank?++ data["newest_event_id"]+ end+def merge_timeline_events(existing, incoming)events_by_id = {}(Array(existing) + Array(incoming)).each do |event|@@ -172,9 +264,106 @@ class TradeRepublicItem::Importerevent = event.with_indifferent_accesskey = event[:id].presence || event- events_by_id[key] = event+ events_by_id[key] = prefer_richer_timeline_event(events_by_id[key], event)+ end+ events_by_id.values.sort_by { |event| event[:timestamp].to_s }+ end++ # Stamp exchange tickers onto timeline details for ISINs that were resolved+ # during sync (including fully sold holdings no longer in the portfolio).+ def apply_instrument_symbols!(events, instrument_symbols)+ return events if instrument_symbols.blank?++ symbols = instrument_symbols.each_with_object({}) do |(isin, mapping), map|+ next if isin.blank? || !mapping.is_a?(Hash)++ entry = mapping.stringify_keys+ symbol = entry["symbol"].to_s.strip.presence+ exchange_slug = entry["exchange_slug"].to_s.strip.upcase.presence+ next if symbol.blank? || exchange_slug.blank?+ next if symbol.casecmp?(isin.to_s)++ map[isin.to_s] = { "symbol" => symbol, "exchange_slug" => exchange_slug }end- events_by_id.values.sort_by { |event| event[:timestamp].to_s }.last(MAX_TIMELINE_EVENTS)+ return events if symbols.empty?++ Array(events).each do |event|+ next unless event.is_a?(Hash)++ detail = event[:detail] || event["detail"]+ next unless detail.is_a?(Hash)++ detail = detail.with_indifferent_access+ isin = detail[:isin].to_s.presence+ next if isin.blank?++ mapping = symbols[isin]+ next unless mapping++ current_symbol = detail[:symbol].to_s.strip.presence+ usable_symbol = current_symbol.present? && !current_symbol.casecmp?(isin)+ detail[:symbol] = mapping["symbol"] unless usable_symbol+ detail[:exchange_slug] = mapping["exchange_slug"] if detail[:exchange_slug].to_s.strip.blank?++ if event.respond_to?(:[]=)+ event[:detail] = detail+ end+ end++ events+ end++ def stamp_symbol_lookup_attempts!(events, unresolved_isins)+ isins = Array(unresolved_isins).map(&:to_s).to_set+ return events if isins.empty?++ now = Time.current.iso8601+ Array(events).each do |event|+ next unless event.is_a?(Hash)++ detail = event[:detail] || event["detail"]+ next unless detail.is_a?(Hash)++ detail = detail.with_indifferent_access+ next unless isins.include?(detail[:isin].to_s)++ detail[Provider::TradeRepublicClient::SYMBOL_LOOKUP_FIRST_ATTEMPTED_AT_KEY] ||= now+ detail[Provider::TradeRepublicClient::SYMBOL_LOOKUP_ATTEMPTED_AT_KEY] = now+ event[:detail] = detail+ end++ events+ end++ def prefer_richer_timeline_event(previous, incoming)+ return incoming if previous.blank?+ return previous if incoming.blank?++ previous = previous.with_indifferent_access+ incoming = incoming.with_indifferent_access+ merged = previous.merge(incoming)+ merged[:category] = incoming[:category].presence || previous[:category]+ merged[:eventType] = incoming[:eventType].presence || previous[:eventType]+ merged[:detail] = prefer_richer_timeline_detail(previous[:detail], incoming[:detail])+ Provider::TradeRepublicTimelineEvent.merge_lifecycle_fields!(merged, previous, incoming)+ # compact drops nil only; boolean false for deleted/hidden must survive.+ merged.compact+ end++ def prefer_richer_timeline_detail(previous, incoming)+ previous = previous.is_a?(Hash) ? previous.with_indifferent_access : {}.with_indifferent_access+ incoming = incoming.is_a?(Hash) ? incoming.with_indifferent_access : {}.with_indifferent_access+ return previous.presence if incoming.blank?+ return incoming.presence if previous.blank?++ previous.merge(incoming) { |_key, old_value, new_value| new_value.presence || old_value }.presence+ end++ def event_category(event)+ return if event.blank?++ event = event.with_indifferent_access if event.respond_to?(:with_indifferent_access)+ event[:category].to_send# Exact decimal math: cash + Σ(quantity × price). Positions lacking adiff --git a/app/models/trade_republic_item/syncer.rb b/app/models/trade_republic_item/syncer.rbindex edacd9ee43..d440cfb208 100644--- a/app/models/trade_republic_item/syncer.rb+++ b/app/models/trade_republic_item/syncer.rb@@ -21,8 +21,8 @@ class TradeRepublicItem::Syncerendsync.update!(status_text: I18n.t("trade_republic_items.sync.status.importing_account")) if sync.respond_to?(:status_text)- trade_republic_item.import_latest_data- collect_trade_republic_quality_stats(sync)+ import_result = trade_republic_item.import_latest_data+ collect_trade_republic_quality_stats(sync, import_result: import_result)sync.update!(status_text: I18n.t("trade_republic_items.sync.status.checking_configuration")) if sync.respond_to?(:status_text)collect_setup_stats(sync, provider_accounts: trade_republic_item.trade_republic_accounts.to_a)@@ -91,13 +91,15 @@ class TradeRepublicItem::Syncertrade_republic_item.trade_republic_accounts.sum { |acct| Array(acct.raw_positions_payload).size }end- def collect_trade_republic_quality_stats(sync)+ def collect_trade_republic_quality_stats(sync, import_result: nil)stats = trade_republic_item.data_quality_summarymerge_sync_stats(sync, {"tr_positions" => stats[:positions],"tr_unpriced_positions" => stats[:unpriced_positions],"tr_events" => stats[:events],- "tr_unknown_events" => stats[:unknown_events]+ "tr_unknown_events" => stats[:unknown_events],+ "tr_pending_trade_details" => stats[:pending_trade_details],+ "tr_detail_backfills" => import_result.is_a?(Hash) ? import_result[:detail_backfill_count].to_i : 0})enddiff --git a/app/views/trade_republic_items/_trade_republic_item.html.erb b/app/views/trade_republic_items/_trade_republic_item.html.erbindex e188d962b3..c879255013 100644--- a/app/views/trade_republic_items/_trade_republic_item.html.erb+++ b/app/views/trade_republic_items/_trade_republic_item.html.erb@@ -105,6 +105,7 @@<span class="text-secondary"><%= t(".data_quality.unpriced", count: quality[:unpriced_positions]) %></span><span class="text-secondary"><%= t(".data_quality.events", count: quality[:events]) %></span><span class="text-secondary"><%= t(".data_quality.unknown", count: quality[:unknown_events]) %></span>+ <span class="text-secondary"><%= t(".data_quality.pending_trade_details", count: quality[:pending_trade_details]) %></span></div><div class="grid gap-2 sm:grid-cols-2 text-xs"><% expense_money = Money.new(expenses[:total].round(2), trade_republic_item.currency) %>diff --git a/config/exchanges.yml b/config/exchanges.ymlindex dd15ebdb69..7b8cc46b6e 100644--- a/config/exchanges.yml+++ b/config/exchanges.yml@@ -122,6 +122,9 @@ XBER:XHAM:name: Hamburgcountry: DE+TGAT:+ name: Tradegate Exchange+ country: DEXDUS:name: Düsseldorfcountry: DEdiff --git a/config/locales/views/trade_republic_items/ca.yml b/config/locales/views/trade_republic_items/ca.ymlindex ceb7260785..66cfa9718c 100644--- a/config/locales/views/trade_republic_items/ca.yml+++ b/config/locales/views/trade_republic_items/ca.yml@@ -37,6 +37,9 @@ ca:unknown:one: "%{count} activitat desconeguda"other: "%{count} activitats desconegudes"+ pending_trade_details:+ one: "%{count} activitat d'inversió pendent de detalls"+ other: "%{count} activitats d'inversió pendents de detalls"expenses:one: "%{count} despesa durant els darrers 30 dies (%{amount})"other: "%{count} despeses durant els darrers 30 dies (%{amount})"@@ -102,5 +105,4 @@ ca:card_fee: Comissió de targetacard_refund: Reemborsament de targetatax_refund: Devolució d'impostos- buy: Compra- sell: Venda+ round_up: Round updiff --git a/config/locales/views/trade_republic_items/de.yml b/config/locales/views/trade_republic_items/de.ymlindex b786037d99..e996b28513 100644--- a/config/locales/views/trade_republic_items/de.yml+++ b/config/locales/views/trade_republic_items/de.yml@@ -39,6 +39,9 @@ de:unknown:one: "%{count} unbekannte Aktivität"other: "%{count} unbekannte Aktivitäten"+ pending_trade_details:+ one: "%{count} Investmentaktivität wartet auf Details"+ other: "%{count} Investmentaktivitäten warten auf Details"expenses:one: "%{count} Ausgabe in den letzten 30 Tagen (%{amount})"other: "%{count} Ausgaben in den letzten 30 Tagen (%{amount})"@@ -139,5 +142,4 @@ de:card_fee: Kartengebührcard_refund: Kartenrückerstattungtax_refund: Steuerrückerstattung- buy: Kauf- sell: Verkauf+ round_up: Round updiff --git a/config/locales/views/trade_republic_items/en.yml b/config/locales/views/trade_republic_items/en.ymlindex 5ba23028a9..943939f5ec 100644--- a/config/locales/views/trade_republic_items/en.yml+++ b/config/locales/views/trade_republic_items/en.yml@@ -41,6 +41,9 @@ en:unknown:one: "%{count} unknown activity"other: "%{count} unknown activities"+ pending_trade_details:+ one: "%{count} investment activity awaiting details"+ other: "%{count} investment activities awaiting details"expenses:one: "%{count} expense in the last 30 days (%{amount})"other: "%{count} expenses in the last 30 days (%{amount})"@@ -170,5 +173,4 @@ en:card_fee: Card feecard_refund: Card refundtax_refund: Tax refund- buy: Buy- sell: Sell+ round_up: Round updiff --git a/config/locales/views/trade_republic_items/es.yml b/config/locales/views/trade_republic_items/es.ymlindex 233d871811..9523cacfb0 100644--- a/config/locales/views/trade_republic_items/es.yml+++ b/config/locales/views/trade_republic_items/es.yml@@ -37,6 +37,9 @@ es:unknown:one: "%{count} actividad desconocida"other: "%{count} actividades desconocidas"+ pending_trade_details:+ one: "%{count} actividad de inversión pendiente de detalles"+ other: "%{count} actividades de inversión pendientes de detalles"expenses:one: "%{count} gasto en los últimos 30 días (%{amount})"other: "%{count} gastos en los últimos 30 días (%{amount})"@@ -102,5 +105,4 @@ es:card_fee: Comisión de tarjetacard_refund: Reembolso de tarjetatax_refund: Devolución de impuestos- buy: Compra- sell: Venta+ round_up: Round updiff --git a/config/locales/views/trade_republic_items/fr.yml b/config/locales/views/trade_republic_items/fr.ymlindex 22fc634dfc..9c9626d20b 100644--- a/config/locales/views/trade_republic_items/fr.yml+++ b/config/locales/views/trade_republic_items/fr.yml@@ -62,6 +62,9 @@ fr:unknown:one: "%{count} activité inconnue"other: "%{count} activités inconnues"+ pending_trade_details:+ one: "%{count} opération d'investissement en attente de détails"+ other: "%{count} opérations d'investissement en attente de détails"expenses:one: "%{count} dépense au cours des 30 derniers jours (%{amount})"other: "%{count} dépenses au cours des 30 derniers jours (%{amount})"@@ -167,8 +170,7 @@ fr:card_fee: Frais de cartecard_refund: Remboursement par cartetax_refund: Remboursement d'impôt- buy: Achat- sell: Vente+ round_up: Round upupdate:pin_required: Saisissez votre code PIN ou mot de passe Trade Republic pour vous réauthentifier.success: Configuration Trade Republic mise à jour avec succès.diff --git a/config/locales/views/trade_republic_items/hu.yml b/config/locales/views/trade_republic_items/hu.ymlindex b99135b9d8..eb07779417 100644--- a/config/locales/views/trade_republic_items/hu.yml+++ b/config/locales/views/trade_republic_items/hu.yml@@ -25,6 +25,9 @@ hu:data_quality:title: "Adatminőség és szinkronizálási részletek"repair: "Importált adatok javítása"+ pending_trade_details:+ one: "%{count} befektetési tétel részletekre vár"+ other: "%{count} befektetési tétel részletekre vár"setup_accounts:page_title: "Trade Republic-fiók beállítása"subtitle: "Kapcsold össze a Trade Republic befektetési számládat."@@ -76,5 +79,4 @@ hu:card_fee: Kártyadíjcard_refund: Kártyás visszatérítéstax_refund: Adó-visszatérítés- buy: Vétel- sell: Eladás+ round_up: Round updiff --git a/config/locales/views/trade_republic_items/it.yml b/config/locales/views/trade_republic_items/it.ymlindex 27ef9d8219..c10375b92a 100644--- a/config/locales/views/trade_republic_items/it.yml+++ b/config/locales/views/trade_republic_items/it.yml@@ -25,6 +25,9 @@ it:data_quality:title: "Qualità dei dati e dettagli della sincronizzazione"repair: "Ripara i dati importati"+ pending_trade_details:+ one: "%{count} operazione di investimento in attesa di dettagli"+ other: "%{count} operazioni di investimento in attesa di dettagli"setup_accounts:page_title: "Configura il conto Trade Republic"subtitle: "Collega il tuo conto d’investimento Trade Republic."@@ -76,5 +79,4 @@ it:card_fee: Commissione cartacard_refund: Rimborso cartatax_refund: Rimborso fiscale- buy: Acquisto- sell: Vendita+ round_up: Round updiff --git a/config/locales/views/trade_republic_items/nb.yml b/config/locales/views/trade_republic_items/nb.ymlindex 4ceadbce48..e06e69ba9b 100644--- a/config/locales/views/trade_republic_items/nb.yml+++ b/config/locales/views/trade_republic_items/nb.yml@@ -25,6 +25,9 @@ nb:data_quality:title: "Datakvalitet og synkroniseringsdetaljer"repair: "Reparer importerte data"+ pending_trade_details:+ one: "%{count} investeringsaktivitet venter på detaljer"+ other: "%{count} investeringsaktiviteter venter på detaljer"setup_accounts:page_title: "Konfigurer Trade Republic-konto"subtitle: "Koble til Trade Republic-investeringskontoen din."@@ -76,5 +79,4 @@ nb:card_fee: Kortgebyrcard_refund: Kortrefusjontax_refund: Skatterefusjon- buy: Kjøp- sell: Salg+ round_up: Round updiff --git a/config/locales/views/trade_republic_items/nl.yml b/config/locales/views/trade_republic_items/nl.ymlindex 9a0603c995..4090179de1 100644--- a/config/locales/views/trade_republic_items/nl.yml+++ b/config/locales/views/trade_republic_items/nl.yml@@ -25,6 +25,9 @@ nl:data_quality:title: "Datakwaliteit en synchronisatiedetails"repair: "Geïmporteerde gegevens herstellen"+ pending_trade_details:+ one: "%{count} beleggingsactiviteit wacht op details"+ other: "%{count} beleggingsactiviteiten wachten op details"setup_accounts:page_title: "Trade Republic-rekening instellen"subtitle: "Koppel je Trade Republic-beleggingsrekening."@@ -76,5 +79,4 @@ nl:card_fee: Kaartkostencard_refund: Kaartterugbetalingtax_refund: Belastingteruggaaf- buy: Koop- sell: Verkoop+ round_up: Round updiff --git a/config/locales/views/trade_republic_items/pl.yml b/config/locales/views/trade_republic_items/pl.ymlindex 52fe17ca2c..7cd95ded64 100644--- a/config/locales/views/trade_republic_items/pl.yml+++ b/config/locales/views/trade_republic_items/pl.yml@@ -9,7 +9,6 @@ pl:trade_republic_items:activities:labels:- buy: Kupnocard_fee: Opłata za kartęcard_payment: Płatność kartącard_refund: Zwrot na kartę@@ -17,7 +16,7 @@ pl:contribution: Wpłatadividend: Dywidendainterest: Odsetki- sell: Sprzedaż+ round_up: Round uptax_refund: Zwrot podatkuwithdrawal: Wypłatacomplete_account_setup:@@ -171,6 +170,11 @@ pl:many: "%{count} wydatków w ciągu ostatnich 30 dni (%{amount})"one: "%{count} wydatek w ciągu ostatnich 30 dni (%{amount})"other: "%{count} wydatków w ciągu ostatnich 30 dni (%{amount})"+ pending_trade_details:+ few: "%{count} transakcje inwestycyjne oczekują na szczegóły"+ many: "%{count} transakcji inwestycyjnych oczekuje na szczegóły"+ one: "%{count} transakcja inwestycyjna oczekuje na szczegóły"+ other: "%{count} transakcji inwestycyjnych oczekuje na szczegóły"positions:few: "%{count} pozycje"many: "%{count} pozycji"diff --git a/config/locales/views/trade_republic_items/pt-BR.yml b/config/locales/views/trade_republic_items/pt-BR.ymlindex 7d05e75fec..dde32772b1 100644--- a/config/locales/views/trade_republic_items/pt-BR.yml+++ b/config/locales/views/trade_republic_items/pt-BR.yml@@ -25,6 +25,9 @@ pt-BR:data_quality:title: "Qualidade dos dados e detalhes da sincronização"repair: "Reparar dados importados"+ pending_trade_details:+ one: "%{count} atividade de investimento aguardando detalhes"+ other: "%{count} atividades de investimento aguardando detalhes"setup_accounts:page_title: "Configurar conta da Trade Republic"subtitle: "Vincule sua conta de investimentos da Trade Republic."@@ -76,5 +79,4 @@ pt-BR:card_fee: Tarifa do cartãocard_refund: Reembolso no cartãotax_refund: Restituição de imposto- buy: Compra- sell: Venda+ round_up: Round updiff --git a/config/locales/views/trade_republic_items/ro.yml b/config/locales/views/trade_republic_items/ro.ymlindex 107c9d557f..efa9dd44af 100644--- a/config/locales/views/trade_republic_items/ro.yml+++ b/config/locales/views/trade_republic_items/ro.yml@@ -25,6 +25,10 @@ ro:data_quality:title: "Calitatea datelor și detalii de sincronizare"repair: "Repară datele importate"+ pending_trade_details:+ one: "%{count} activitate de investiții așteaptă detalii"+ few: "%{count} activități de investiții așteaptă detalii"+ other: "%{count} de activități de investiții așteaptă detalii"setup_accounts:page_title: "Configurează contul Trade Republic"subtitle: "Asociază contul tău de investiții Trade Republic."@@ -78,5 +82,4 @@ ro:card_fee: Comision cardcard_refund: Rambursare pe cardtax_refund: Rambursare fiscală- buy: Cumpărare- sell: Vânzare+ round_up: Round updiff --git a/config/locales/views/trade_republic_items/ru.yml b/config/locales/views/trade_republic_items/ru.ymlindex da67e188a9..fa0661e932 100644--- a/config/locales/views/trade_republic_items/ru.yml+++ b/config/locales/views/trade_republic_items/ru.yml@@ -45,6 +45,11 @@ ru:few: '%{count} неизвестные операции'many: '%{count} неизвестных операций'other: '%{count} неизвестные операции'+ pending_trade_details:+ one: '%{count} инвестиционная операция ожидает деталей'+ few: '%{count} инвестиционные операции ожидают деталей'+ many: '%{count} инвестиционных операций ожидают деталей'+ other: '%{count} инвестиционной операции ожидают деталей'expenses:one: '%{count} трата за последние 30 дней (%{amount})'few: '%{count} траты за последние 30 дней (%{amount})'@@ -160,8 +165,7 @@ ru:card_fee: Комиссия по картеcard_refund: Возврат на картуtax_refund: Налоговый возврат- buy: Покупка- sell: Продажа+ round_up: Round updefaults:name: Trade Republicsync_status:diff --git a/config/locales/views/trade_republic_items/tr.yml b/config/locales/views/trade_republic_items/tr.ymlindex 820879baf1..6dcfb430af 100644--- a/config/locales/views/trade_republic_items/tr.yml+++ b/config/locales/views/trade_republic_items/tr.yml@@ -37,6 +37,9 @@ tr:unknown:one: "%{count} bilinmeyen işlem"other: "%{count} bilinmeyen işlem"+ pending_trade_details:+ one: '%{count} yatırım işlemi ayrıntı bekliyor'+ other: '%{count} yatırım işlemi ayrıntı bekliyor'expenses:one: "Son 30 günde %{count} gider (%{amount})"other: "Son 30 günde %{count} gider (%{amount})"@@ -144,8 +147,7 @@ tr:card_fee: Kart ücreticard_refund: Kart iadesitax_refund: Vergi iadesi- buy: Alış- sell: Satış+ round_up: Round updefaults:name: Trade Republicsync_status:diff --git a/config/locales/views/trade_republic_items/uk.yml b/config/locales/views/trade_republic_items/uk.ymlindex 9e1c280216..fc5ce3d0c6 100644--- a/config/locales/views/trade_republic_items/uk.yml+++ b/config/locales/views/trade_republic_items/uk.yml@@ -45,6 +45,11 @@ uk:few: "%{count} невідомі операції"many: "%{count} невідомих операцій"other: "%{count} невідомі операції"+ pending_trade_details:+ one: '%{count} інвестиційна операція очікує деталей'+ few: '%{count} інвестиційні операції очікують деталей'+ many: '%{count} інвестиційних операцій очікують деталей'+ other: '%{count} інвестиційної операції очікують деталей'expenses:one: "%{count} витрата за останні 30 днів (%{amount})"few: "%{count} витрати за останні 30 днів (%{amount})"@@ -160,8 +165,7 @@ uk:card_fee: Комісія за карткуcard_refund: Повернення на карткуtax_refund: Повернення податку- buy: Купівля- sell: Продаж+ round_up: Round updefaults:name: Trade Republicsync_status:diff --git a/config/locales/views/trade_republic_items/vi.yml b/config/locales/views/trade_republic_items/vi.ymlindex d6712e884d..42ea9a73f3 100644--- a/config/locales/views/trade_republic_items/vi.yml+++ b/config/locales/views/trade_republic_items/vi.yml@@ -37,6 +37,9 @@ vi:unknown:one: "%{count} hoạt động không xác định"other: "%{count} hoạt động không xác định"+ pending_trade_details:+ one: "%{count} giao dịch đầu tư đang chờ chi tiết"+ other: "%{count} giao dịch đầu tư đang chờ chi tiết"expenses:one: "%{count} khoản chi trong 30 ngày qua (%{amount})"other: "%{count} khoản chi trong 30 ngày qua (%{amount})"@@ -102,5 +105,4 @@ vi:card_fee: Phí thẻcard_refund: Hoàn tiền thẻtax_refund: Hoàn thuế- buy: Mua- sell: Bán+ round_up: Round updiff --git a/config/locales/views/trade_republic_items/zh-CN.yml b/config/locales/views/trade_republic_items/zh-CN.ymlindex 08ee9dac6c..64b8ad8481 100644--- a/config/locales/views/trade_republic_items/zh-CN.yml+++ b/config/locales/views/trade_republic_items/zh-CN.yml@@ -37,6 +37,9 @@ zh-CN:unknown:one: "%{count} 条未知活动"other: "%{count} 条未知活动"+ pending_trade_details:+ one: "%{count} 项投资活动等待详情"+ other: "%{count} 项投资活动等待详情"expenses:one: "过去 30 天 %{count} 笔支出(%{amount})"other: "过去 30 天 %{count} 笔支出(%{amount})"@@ -102,5 +105,4 @@ zh-CN:card_fee: 卡费card_refund: 卡退款tax_refund: 退税- buy: 买入- sell: 卖出+ round_up: Round updiff --git a/config/locales/views/trade_republic_items/zh-TW.yml b/config/locales/views/trade_republic_items/zh-TW.ymlindex 5c244f4356..b8cd3d88c1 100644--- a/config/locales/views/trade_republic_items/zh-TW.yml+++ b/config/locales/views/trade_republic_items/zh-TW.yml@@ -37,6 +37,9 @@ zh-TW:unknown:one: "%{count} 筆未知活動"other: "%{count} 筆未知活動"+ pending_trade_details:+ one: "%{count} 項投資活動等待詳細資料"+ other: "%{count} 項投資活動等待詳細資料"expenses:one: "過去 30 天 %{count} 筆支出(%{amount})"other: "過去 30 天 %{count} 筆支出(%{amount})"@@ -102,5 +105,4 @@ zh-TW:card_fee: 卡片費用card_refund: 卡片退款tax_refund: 退稅- buy: 買入- sell: 賣出+ round_up: Round updiff --git a/test/i18n_test.rb b/test/i18n_test.rbindex edbfeaf64d..9e0d590b63 100644--- a/test/i18n_test.rb+++ b/test/i18n_test.rb@@ -80,18 +80,19 @@ class I18nTest < ActiveSupport::TestCasedef test_trade_republic_activity_labels_exist_for_each_localerequired_labels = %w[contribution withdrawal interest dividend card_payment cash_withdrawal- card_fee card_refund tax_refund buy sell+ card_fee card_refund tax_refund round_up]Dir[File.expand_path("../config/locales/views/trade_republic_items/*.yml", __dir__)].sort.each do |file|locale = File.basename(file, ".yml")- labels = YAML.load_file(file, aliases: true)- .fetch(locale)- .dig("trade_republic_items", "activities", "labels")+ translations = YAML.load_file(file, aliases: true).fetch(locale)+ labels = translations.dig("trade_republic_items", "activities", "labels")assert labels.is_a?(Hash), "#{file} must define trade_republic_items.activities.labels"assert_empty required_labels - labels.keys,"#{file} is missing Trade Republic activity labels"+ assert translations.dig("trade_republic_items", "trade_republic_item", "data_quality", "pending_trade_details").present?,+ "#{file} is missing trade_republic_item.data_quality.pending_trade_details"endenddiff --git a/test/models/trade_republic_account_activities_processor_test.rb b/test/models/trade_republic_account_activities_processor_test.rbindex 84e12940c1..ada0025c5e 100644--- a/test/models/trade_republic_account_activities_processor_test.rb+++ b/test/models/trade_republic_account_activities_processor_test.rb@@ -40,6 +40,109 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_equal BigDecimal("13.439945").to_s, trade.entryable.qty.to_send+ test "trade names use quantity and instrument without buy or sell wording" do+ Security.create!(ticker: "ISPA", exchange_operating_mic: "XETR", name: "Old security name")+ event = order_execution_detail(+ event_id: "evt_trade_name", quantity: "0.623752", isin: "IE00B3RBWM25", amount: "25.00"+ ).deep_merge(detail: {+ name: "STOXX Global Dividend 100 EUR (Dist)", symbol: "ISPA", exchange_slug: "XETR"+ })++ import_event(event)++ entry = find_trade("trade_republic_event_evt_trade_name")+ assert_equal "ISPA · 0.623752x STOXX Global Dividend 100 EUR (Dist)", entry.name++ import_event(event)++ assert_equal entry.id, find_trade("trade_republic_event_evt_trade_name").id+ assert_equal "ISPA · 0.623752x STOXX Global Dividend 100 EUR (Dist)", entry.reload.name+ end++ test "sell names fall back to the ticker without repeating it" do+ event = order_execution_detail(+ event_id: "evt_ticker_name", quantity: "-20.0", isin: "IE00B3RBWM25", amount: "80.00"+ ).deep_merge(detail: { name: nil })++ import_event(event)++ assert_equal "IE00B3RBWM25 · 20x", find_trade("trade_republic_event_evt_ticker_name").name+ end++ test "trade reuses exchange symbol fetched for its portfolio position" do+ Security.stubs(:search_provider).returns([])+ @tr_account.update!(raw_positions_payload: [+ {+ "isin" => "DE000BASF111",+ "name" => "BASF",+ "quantity" => "5",+ "price" => "45.12",+ "symbol" => "BAS",+ "exchange_slug" => "XETR"+ }+ ])++ import_event(order_execution_detail(+ event_id: "evt_symbol",+ quantity: "2",+ isin: "DE000BASF111",+ amount: "90.24"+ ))++ trade = find_trade("trade_republic_event_evt_symbol")+ assert_equal "BAS", trade.entryable.security.ticker+ assert_equal "XETR", trade.entryable.security.exchange_operating_mic+ assert_not trade.entryable.security.offline?+ end++ test "trade with symbol in detail resolves sold ISIN to exchange ticker" do+ Security.stubs(:search_provider).returns([])++ import_event(order_execution_detail(+ event_id: "evt_sold_symbol",+ quantity: "-10",+ isin: "NL0000303709",+ amount: "150.00"+ ).deep_merge(detail: { symbol: "ABN", exchange_slug: "XETR", name: "ABN AMRO" }))++ trade = find_trade("trade_republic_event_evt_sold_symbol")+ assert_equal "ABN", trade.entryable.security.ticker+ assert_equal "XETR", trade.entryable.security.exchange_operating_mic+ assert_not trade.entryable.security.offline?+ assert_not_includes trade.name, "NL0000303709"+ assert_includes trade.name, "ABN"+ end++ test "reprocessing rematches prior ISIN trades when detail gains an exchange symbol" do+ Security.stubs(:search_provider).returns([])++ import_event(order_execution_detail(+ event_id: "evt_rematch",+ quantity: "-3",+ isin: "DE000A0F5UJ7",+ amount: "90.00"+ ))++ first = find_trade("trade_republic_event_evt_rematch")+ assert_equal "DE000A0F5UJ7", first.entryable.security.ticker+ assert first.entryable.security.offline?+ assert_includes first.name, "DE000A0F5UJ7"++ import_event(order_execution_detail(+ event_id: "evt_rematch",+ quantity: "-3",+ isin: "DE000A0F5UJ7",+ amount: "90.00"+ ).deep_merge(detail: { symbol: "EXV1", exchange_slug: "XETR", name: "STOXX Banks" }))++ rematched = find_trade("trade_republic_event_evt_rematch")+ assert_equal "EXV1", rematched.entryable.security.ticker+ assert_equal "XETR", rematched.entryable.security.exchange_operating_mic+ assert_not rematched.entryable.security.offline?+ assert_not_includes rematched.name, "DE000A0F5UJ7"+ assert_includes rematched.name, "EXV1"+ end+test "sell imports negative quantity and positive amount" doimport_event(order_execution_detail(event_id: "evt_sell",@@ -203,14 +306,118 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_not Entry.exists?(external_id: "trade_republic_event_evt_unknown")end- test "trade fee is retained as metadata and not imported as a second cash entry" do- import_event(order_execution_detail(quantity: "1.5", isin: "US0378331005", amount: "100.00").deep_merge(detail: { fees: "1.00" }))+ test "trade fee is imported on the trade and excluded from per-share price" do+ import_event(order_execution_detail(+ quantity: "2",+ isin: "IE00B5BMR087",+ amount: "1024.92"+ ).deep_merge(detail: { fees: "1.00", price: "511.96", name: "Core S&P 500" }))assert_equal 1, Entry.where(source: "trade_republic").counttrade = find_trade("trade_republic_event_evt_buy")+ assert_equal BigDecimal("511.96"), trade.entryable.price+ assert_equal BigDecimal("1.00"), trade.entryable.fee+ assert_equal BigDecimal("-1024.92"), trade.amountassert_equal "1.00", trade.entryable.extra.dig("trade_republic", "fees")end+ test "trade derives share price from amount net of fees when price is missing" do+ import_event(order_execution_detail(+ quantity: "2",+ isin: "IE00B5BMR087",+ amount: "1024.92"+ ).deep_merge(detail: { fees: "1.00" }))++ trade = find_trade("trade_republic_event_evt_buy")+ assert_equal BigDecimal("511.96"), trade.entryable.price+ assert_equal BigDecimal("1.00"), trade.entryable.fee+ end++ test "sell fallback amount subtracts fee from proceeds" do+ Security.stubs(:search_provider).returns([])++ import_event(order_execution_detail(+ event_id: "evt_sell_fee",+ quantity: "-2",+ isin: "IE00B5BMR087",+ amount: nil+ ).deep_merge(detail: { fees: "1.00", price: "511.96", name: "Core S&P 500" }))++ trade = find_trade("trade_republic_event_evt_sell_fee")+ assert_not_nil trade+ assert_equal BigDecimal("511.96"), trade.entryable.price+ assert_equal BigDecimal("1.00"), trade.entryable.fee+ assert_equal BigDecimal("1022.92"), trade.amount+ assert_equal "Sell", trade.entryable.investment_activity_label+ end++ test "sell derives share price from proceeds plus fee when price is missing" do+ import_event(order_execution_detail(+ event_id: "evt_sell_derive",+ quantity: "-2",+ isin: "IE00B5BMR087",+ amount: "1022.92"+ ).deep_merge(detail: { fees: "1.00" }))++ trade = find_trade("trade_republic_event_evt_sell_derive")+ assert_equal BigDecimal("511.96"), trade.entryable.price+ assert_equal BigDecimal("1.00"), trade.entryable.fee+ assert_equal BigDecimal("1022.92"), trade.amount+ end++ test "buy and sell fallbacks include taxes alongside fees" do+ Security.stubs(:search_provider).returns([])++ import_event(order_execution_detail(+ event_id: "evt_buy_tax",+ quantity: "2",+ isin: "IE00B5BMR087",+ amount: nil+ ).deep_merge(detail: { fees: "1.00", taxes: "0.50", price: "511.96", name: "Core S&P 500" }))++ buy = find_trade("trade_republic_event_evt_buy_tax")+ assert_equal BigDecimal("511.96"), buy.entryable.price+ assert_equal BigDecimal("1.00"), buy.entryable.fee+ assert_equal BigDecimal("-1025.42"), buy.amount # 2*511.96 + 1 + 0.50++ import_event(order_execution_detail(+ event_id: "evt_sell_tax",+ quantity: "-2",+ isin: "IE00B5BMR087",+ amount: "1022.42"+ ).deep_merge(detail: { fees: "1.00", taxes: "0.50" }))++ sell = find_trade("trade_republic_event_evt_sell_tax")+ # Sell cash 1022.42 = gross - fee - tax → price (1022.42+1.50)/2+ assert_equal BigDecimal("511.96"), sell.entryable.price+ assert_equal BigDecimal("1.00"), sell.entryable.fee+ assert_equal BigDecimal("1022.42"), sell.amount+ end++ test "reprocessing updates fee and share price on an existing trade" do+ import_event(order_execution_detail(+ event_id: "evt_fee_update",+ quantity: "2",+ isin: "IE00B5BMR087",+ amount: "1024.92"+ ))++ first = find_trade("trade_republic_event_evt_fee_update")+ assert_equal BigDecimal("512.46"), first.entryable.price+ assert_equal 0, first.entryable.fee.to_d++ import_event(order_execution_detail(+ event_id: "evt_fee_update",+ quantity: "2",+ isin: "IE00B5BMR087",+ amount: "1024.92"+ ).deep_merge(detail: { fees: "1.00", price: "511.96" }))++ updated = find_trade("trade_republic_event_evt_fee_update")+ assert_equal BigDecimal("511.96"), updated.entryable.price+ assert_equal BigDecimal("1.00"), updated.entryable.fee+ end+test "event without normalized detail is skipped" doassert_no_difference "Entry.count" doimport_event({@@ -275,8 +482,721 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert Entry.exists?(external_id: "trade_republic_event_unknown_evt")end+ test "saveback imports as a portfolio trade and never as a cash transaction when split" do+ cash_account, cash_sure = create_linked_cash_account!++ saveback = saveback_event+ @tr_account.update!(raw_timeline_payload: [ saveback ])+ cash_account.update!(raw_timeline_payload: [ saveback ])++ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ trade = find_trade("trade_republic_event_evt_saveback")+ assert_not_nil trade+ assert_equal "Trade", trade.entryable_type+ assert_equal BigDecimal("0.09329"), trade.entryable.qty+ assert_equal "Buy", trade.entryable.investment_activity_label+ assert_equal BigDecimal("-3.74"), trade.amount+ assert_equal "SAVEBACK_AGGREGATE", trade.entryable.extra.dig("trade_republic", "event_type")++ assert_not Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_saveback")+ end++ test "round up imports as a portfolio trade and a cash outflow when split" do+ cash_account, cash_sure = create_linked_cash_account!++ round_up = round_up_event+ @tr_account.update!(raw_timeline_payload: [ round_up ])+ cash_account.update!(raw_timeline_payload: [ round_up ])++ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ trade = find_trade("trade_republic_event_evt_round_up")+ assert_not_nil trade+ assert_equal "Trade", trade.entryable_type+ assert_equal BigDecimal("0.009977"), trade.entryable.qty+ assert_equal BigDecimal("-0.40"), trade.amount+ assert_equal "SPARE_CHANGE_AGGREGATE", trade.entryable.extra.dig("trade_republic", "event_type")++ cash_entry = Entry.find_by(account: cash_sure, external_id: "trade_republic_event_evt_round_up")+ assert_not_nil cash_entry+ assert_equal "Transaction", cash_entry.entryable_type+ assert_equal BigDecimal("0.40"), cash_entry.amount+ assert_equal "Round up", cash_entry.transaction.investment_activity_label+ assert_equal "SPARE_CHANGE_AGGREGATE", cash_entry.transaction.extra.dig("trade_republic", "event_type")+ end++ test "round up and saveback remain idempotent across repeated processing" do+ cash_account, cash_sure = create_linked_cash_account!+ events = [ saveback_event, round_up_event ]++ @tr_account.update!(raw_timeline_payload: events)+ cash_account.update!(raw_timeline_payload: events)++ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_difference -> { @account.entries.where(source: "trade_republic").count }, 0 do+ assert_difference -> { cash_sure.entries.where(source: "trade_republic").count }, 0 do+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ end+ end++ assert_equal 2, @account.entries.where(entryable_type: "Trade", source: "trade_republic").count+ assert_equal 1, cash_sure.entries.where(entryable_type: "Transaction", source: "trade_republic").count+ end++ test "incomplete saveback details are skipped on portfolio and never become cash" do+ cash_account, cash_sure = create_linked_cash_account!+ incomplete = saveback_event.deep_merge(detail: { isin: nil, quantity: nil })++ @tr_account.update!(raw_timeline_payload: [ incomplete ])+ cash_account.update!(raw_timeline_payload: [ incomplete ])++ assert_no_difference "Entry.where(source: 'trade_republic').count" do+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ end++ assert_not Entry.exists?(account: @account, external_id: "trade_republic_event_evt_saveback")+ assert_not Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_saveback")+ end++ test "incomplete round up details still import cash but skip the portfolio trade" do+ cash_account, cash_sure = create_linked_cash_account!+ incomplete = round_up_event.deep_merge(detail: { isin: nil, quantity: nil })++ @tr_account.update!(raw_timeline_payload: [ incomplete ])+ cash_account.update!(raw_timeline_payload: [ incomplete ])++ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_not Entry.exists?(account: @account, external_id: "trade_republic_event_evt_round_up")++ cash_entry = Entry.find_by(account: cash_sure, external_id: "trade_republic_event_evt_round_up")+ assert_not_nil cash_entry+ assert_equal BigDecimal("0.40"), cash_entry.amount+ assert_equal "Round up", cash_entry.transaction.investment_activity_label+ end++ test "portfolio-only saveback and round up import as trades without cash entries" do+ @tr_account.update!(raw_timeline_payload: [ saveback_event, round_up_event ])++ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process++ assert_equal 2, @account.entries.where(entryable_type: "Trade", source: "trade_republic").count+ assert_equal 0, @account.entries.where(entryable_type: "Transaction", source: "trade_republic").count+ end++ test "cash-only round up imports as cash while saveback is skipped" do+ @tr_account.destroy+ cash_provider = @item.trade_republic_accounts.create!(+ name: "Cash only",+ kind: "cash",+ trade_republic_account_id: "cash:DEPROC1",+ currency: "EUR",+ raw_timeline_payload: [ saveback_event, round_up_event ]+ )+ cash_sure = @family.accounts.create!(+ name: "Trade Republic Cash Only",+ balance: 0,+ cash_balance: 0,+ currency: "EUR",+ accountable: Depository.new+ )+ cash_provider.ensure_account_provider!(cash_sure)++ TradeRepublicAccount::ActivitiesProcessor.new(cash_provider.reload).process++ assert_not Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_saveback")+ cash_entry = Entry.find_by(account: cash_sure, external_id: "trade_republic_event_evt_round_up")+ assert_not_nil cash_entry+ assert_equal BigDecimal("0.40"), cash_entry.amount+ end++ test "reconciles unprotected legacy saveback cash transactions" do+ cash_account, cash_sure = create_linked_cash_account!+ saveback = saveback_event++ Account::ProviderImportAdapter.new(cash_sure).import_transaction(+ external_id: "trade_republic_event_evt_saveback",+ amount: BigDecimal("3.74"),+ currency: "EUR",+ date: Date.parse("2026-09-02"),+ name: "STOXX Global Dividend 100 EUR (Dist)",+ source: "trade_republic",+ investment_activity_label: "Withdrawal",+ extra: {+ trade_republic: {+ event_id: "trade_republic_event_evt_saveback",+ event_type: "SAVEBACK_AGGREGATE",+ title: "STOXX Global Dividend 100 EUR (Dist)",+ subtitle: "Saveback"+ }+ }+ )++ cash_account.update!(raw_timeline_payload: [ saveback ])+ @tr_account.update!(raw_timeline_payload: [ saveback ])++ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert Entry.exists?(account: @account, external_id: "trade_republic_event_evt_saveback", entryable_type: "Trade")+ assert_not Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_saveback")+ end++ test "keeps legacy saveback cash until the portfolio trade is imported" do+ cash_account, cash_sure = create_linked_cash_account!+ incomplete = saveback_event.deep_merge(detail: { isin: nil, quantity: nil })++ Account::ProviderImportAdapter.new(cash_sure).import_transaction(+ external_id: "trade_republic_event_evt_saveback",+ amount: BigDecimal("3.74"),+ currency: "EUR",+ date: Date.parse("2026-09-02"),+ name: "STOXX Global Dividend 100 EUR (Dist)",+ source: "trade_republic",+ investment_activity_label: "Withdrawal",+ extra: {+ trade_republic: {+ event_id: "trade_republic_event_evt_saveback",+ event_type: "SAVEBACK_AGGREGATE",+ title: "STOXX Global Dividend 100 EUR (Dist)",+ subtitle: "Saveback"+ }+ }+ )++ cash_account.update!(raw_timeline_payload: [ incomplete ])+ @tr_account.update!(raw_timeline_payload: [ incomplete ])++ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_not Entry.exists?(account: @account, external_id: "trade_republic_event_evt_saveback")+ assert Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_saveback", entryable_type: "Transaction")+ end++ test "preserves protected legacy saveback cash transactions during reconciliation" do+ cash_account, cash_sure = create_linked_cash_account!+ saveback = saveback_event++ entry = Account::ProviderImportAdapter.new(cash_sure).import_transaction(+ external_id: "trade_republic_event_evt_saveback",+ amount: BigDecimal("3.74"),+ currency: "EUR",+ date: Date.parse("2026-09-02"),+ name: "STOXX Global Dividend 100 EUR (Dist)",+ source: "trade_republic",+ investment_activity_label: "Withdrawal",+ extra: {+ trade_republic: {+ event_id: "trade_republic_event_evt_saveback",+ event_type: "SAVEBACK_AGGREGATE"+ }+ }+ )+ entry.mark_user_modified!++ # Portfolio trade is already present so the missing-trade guard would not+ # keep this cash row — protection alone must preserve it.+ cash_account.update!(raw_timeline_payload: [ saveback ])+ @tr_account.update!(raw_timeline_payload: [ saveback ])+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ assert Entry.exists?(account: @account, external_id: "trade_republic_event_evt_saveback", entryable_type: "Trade")++ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_saveback")+ assert entry.reload.user_modified?+ end++ test "savings-plan invoice imports as a portfolio trade and never as cash" do+ cash_account, cash_sure = create_linked_cash_account!+ event = savings_plan_invoice_event++ @tr_account.update!(raw_timeline_payload: [ event ])+ cash_account.update!(raw_timeline_payload: [ event ])++ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ trade = find_trade("trade_republic_event_evt_savings_plan")+ assert_not_nil trade+ assert_equal "Trade", trade.entryable_type+ assert_equal BigDecimal("0.25"), trade.entryable.qty+ assert_equal "Buy", trade.entryable.investment_activity_label+ assert_equal BigDecimal("-25.00"), trade.amount+ assert_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")+ end++ test "savings-plan invoice remains idempotent across repeated processing" do+ cash_account, cash_sure = create_linked_cash_account!+ event = savings_plan_invoice_event++ @tr_account.update!(raw_timeline_payload: [ event ])+ cash_account.update!(raw_timeline_payload: [ event ])++ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_difference -> { @account.entries.where(source: "trade_republic").count }, 0 do+ assert_difference -> { cash_sure.entries.where(source: "trade_republic").count }, 0 do+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ end+ end++ assert_equal 1, @account.entries.where(entryable_type: "Trade", source: "trade_republic").count+ assert_equal 0, cash_sure.entries.where(source: "trade_republic").count+ end++ test "savings-plan invoice duplicated by an execution event imports once" do+ invoice = savings_plan_invoice_event+ execution = savings_plan_invoice_event.merge(+ id: "evt_savings_execution",+ timestamp: "2026-06-17T10:00:05Z",+ eventType: "TRADING_SAVINGSPLAN_EXECUTED"+ )++ @tr_account.update!(raw_timeline_payload: [ invoice, execution ])+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process++ assert_nil find_trade("trade_republic_event_evt_savings_plan")+ assert_not_nil find_trade("trade_republic_event_evt_savings_execution")+ end++ test "failed savings-plan executions remain ignored" do+ cash_account, = create_linked_cash_account!+ failed = {+ id: "evt_savings_failed",+ timestamp: "2026-06-17T10:00:00Z",+ eventType: "TRADING_SAVINGSPLAN_EXECUTION_FAILED",+ title: "MSCI World",+ detail: { amount: -25.0, currency: "EUR" }+ }++ @tr_account.update!(raw_timeline_payload: [ failed ])+ cash_account.update!(raw_timeline_payload: [ failed ])++ assert_no_difference "Entry.where(source: 'trade_republic').count" do+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ end++ assert_not Entry.exists?(external_id: "trade_republic_event_evt_savings_failed")+ end++ test "incomplete savings-plan event is skipped until backfill enriches the same stored event" do+ incomplete = savings_plan_invoice_event.deep_merge(detail: { isin: nil, quantity: nil })+ @tr_account.update!(raw_timeline_payload: [ incomplete ])++ assert_no_difference "Entry.where(source: 'trade_republic').count" do+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ end+ assert_not Entry.exists?(account: @account, external_id: "trade_republic_event_evt_savings_plan")++ @tr_account.update!(raw_timeline_payload: [ savings_plan_invoice_event ])+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process++ trade = find_trade("trade_republic_event_evt_savings_plan")+ assert_not_nil trade+ assert_equal BigDecimal("0.25"), trade.entryable.qty+ assert_equal BigDecimal("-25.00"), trade.amount+ end++ test "executed card payments import while declined cards are skipped" do+ cash_account, cash_sure = create_linked_cash_account!+ cash_account.update!(raw_timeline_payload: [+ {+ id: "evt_card_ok",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "CARD_TRANSACTION",+ category: "POC_CREATED",+ status: "EXECUTED",+ title: "Coffee",+ detail: { amount: "4.50", currency: "EUR" }+ },+ {+ id: "evt_card_declined",+ timestamp: "2026-08-01T11:00:00Z",+ eventType: "CARD_TRANSACTION",+ category: "POC_CREATED",+ status: "DECLINED",+ title: "Blocked",+ detail: { amount: "99.00", currency: "EUR" }+ }+ ])++ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_card_ok")+ assert_not Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_card_declined")+ end++ test "blank status with declined subtitle skips import without matching security titles" do+ cash_account, cash_sure = create_linked_cash_account!+ cash_account.update!(raw_timeline_payload: [+ {+ id: "evt_subtitle_declined",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "CARD_TRANSACTION",+ category: "POC_CREATED",+ title: "Coffee Shop",+ subtitle: "Payment declined",+ detail: { amount: "12.00", currency: "EUR" }+ },+ {+ id: "evt_title_cancel_ok",+ timestamp: "2026-08-01T11:00:00Z",+ eventType: "CARD_TRANSACTION",+ category: "POC_CREATED",+ title: "Cancellation Fee Shop",+ subtitle: "Card payment",+ detail: { amount: "3.00", currency: "EUR" }+ }+ ])++ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_not Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_subtitle_declined")+ assert Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_title_cancel_ok")+ end++ test "blank status declined subtitle keeps prior imports" do+ cash_account, cash_sure = create_linked_cash_account!+ Account::ProviderImportAdapter.new(cash_sure).import_transaction(+ external_id: "trade_republic_event_evt_later_declined",+ amount: BigDecimal("12.00"),+ currency: "EUR",+ date: Date.parse("2026-08-01"),+ name: "Pending card",+ source: "trade_republic",+ investment_activity_label: "Card payment"+ )++ cash_account.update!(raw_timeline_payload: [ {+ id: "evt_later_declined",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "CARD_TRANSACTION",+ category: "POC_CREATED",+ title: "Coffee",+ subtitle: "Transaction failed",+ detail: { amount: "12.00", currency: "EUR" }+ } ])++ assert_difference -> { DebugLogEntry.where("message LIKE ?", "%flagged only by its subtitle%").count }, 1 do+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ end++ assert Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_later_declined")+ end++ test "hidden events remove unprotected prior imports" do+ cash_account, cash_sure = create_linked_cash_account!+ Account::ProviderImportAdapter.new(cash_sure).import_transaction(+ external_id: "trade_republic_event_evt_card_hidden",+ amount: BigDecimal("12.00"),+ currency: "EUR",+ date: Date.parse("2026-08-01"),+ name: "Hidden card",+ source: "trade_republic",+ investment_activity_label: "Card payment"+ )++ cash_account.update!(raw_timeline_payload: [ {+ id: "evt_card_hidden",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "CARD_TRANSACTION",+ category: "POC_CREATED",+ title: "Coffee",+ hidden: true,+ detail: { amount: "12.00", currency: "EUR" }+ } ])++ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_not Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_card_hidden")+ end++ test "deleted financial events are skipped and unprotected prior imports are removed" do+ cash_account, cash_sure = create_linked_cash_account!+ Account::ProviderImportAdapter.new(cash_sure).import_transaction(+ external_id: "trade_republic_event_evt_card_deleted",+ amount: BigDecimal("12.00"),+ currency: "EUR",+ date: Date.parse("2026-08-01"),+ name: "Ghost payment",+ source: "trade_republic",+ investment_activity_label: "Card payment"+ )++ cash_account.update!(raw_timeline_payload: [ {+ id: "evt_card_deleted",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "CARD_TRANSACTION",+ category: "POC_CREATED",+ deleted: true,+ title: "Ghost payment",+ detail: { amount: "12.00", currency: "EUR" }+ } ])++ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_not Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_card_deleted")+ end++ test "hidden financial events are skipped and unprotected prior imports are removed" do+ cash_account, cash_sure = create_linked_cash_account!+ Account::ProviderImportAdapter.new(cash_sure).import_transaction(+ external_id: "trade_republic_event_evt_card_hidden",+ amount: BigDecimal("12.00"),+ currency: "EUR",+ date: Date.parse("2026-08-01"),+ name: "Hidden payment",+ source: "trade_republic",+ investment_activity_label: "Card payment"+ )++ cash_account.update!(raw_timeline_payload: [ {+ id: "evt_card_hidden",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "CARD_TRANSACTION",+ category: "POC_CREATED",+ hidden: true,+ title: "Hidden payment",+ detail: { amount: "12.00", currency: "EUR" }+ } ])++ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_not Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_card_hidden")+ end++ test "administrative and created-order events are ignored without logging or importing" do+ cash_account, = create_linked_cash_account!+ cash_account.update!(raw_timeline_payload: [+ {+ id: "evt_card_verify",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "CARD_VERIFICATION",+ title: "Card verification"+ },+ {+ id: "evt_limit_buy_created",+ timestamp: "2026-09-22T13:36:39Z",+ eventType: "TRADING_ORDER_CREATED",+ title: "SanDisk",+ subtitle: "Limit buy created"+ }+ ])++ assert_no_difference "DebugLogEntry.count" do+ assert_no_difference "Entry.where(source: 'trade_republic').count" do+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ end+ end+ end++ test "Google Pay inbound deposits import as contributions" do+ cash_account, cash_sure = create_linked_cash_account!+ cash_account.update!(raw_timeline_payload: [ {+ id: "evt_gpay",+ timestamp: "2024-03-28T08:29:35Z",+ eventType: "PAYMENT_INBOUND_GOOGLE_PAY",+ title: "Cash in",+ detail: { amount: "50.00", currency: "EUR" }+ } ])++ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ entry = 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+ end++ test "Legal documents title without event type is ignored silently" do+ cash_account, = create_linked_cash_account!+ cash_account.update!(raw_timeline_payload: [ {+ id: "evt_legal",+ timestamp: "2026-07-28T12:42:32Z",+ title: "Legal documents",+ subtitle: "Accepted"+ } ])++ assert_no_difference "DebugLogEntry.count" do+ assert_no_difference "Entry.where(source: 'trade_republic').count" do+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ end+ end+ end++ test "truly unknown financial mapping gaps are logged once without creating entries" do+ cash_account, = create_linked_cash_account!+ cash_account.update!(raw_timeline_payload: [ {+ id: "evt_mapping_gap",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "BRAND_NEW_MAPPING_GAP",+ title: "Mystery payout",+ status: "EXECUTED"+ } ])++ assert_difference "DebugLogEntry.count", 1 do+ assert_no_difference "Entry.where(source: 'trade_republic').count" do+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ end+ end++ log = DebugLogEntry.order(:created_at).last+ assert_match(/unsupported timeline event/i, log.message)+ assert_equal "BRAND_NEW_MAPPING_GAP", log.metadata["event_type"]+ assert_equal "EXECUTED", log.metadata["status"]+ end++ test "unknown events are logged once across split portfolio and cash accounts" do+ cash_account, = create_linked_cash_account!+ event = {+ id: "evt_split_gap",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "BRAND_NEW_MAPPING_GAP",+ title: "Mystery payout"+ }+ @tr_account.update!(raw_timeline_payload: [ event ])+ cash_account.update!(raw_timeline_payload: [ event ])++ assert_difference -> { DebugLogEntry.where("message LIKE ?", "%unsupported timeline event%").count }, 1 do+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ end+ end++ test "price backfill attempt marker stays out of the transaction provider detail" do+ cash_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" }+ ) ])++ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ entry = 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)+ end++ test "preserves protected entries when reconciling declined upstream events" do+ cash_account, cash_sure = create_linked_cash_account!+ entry = Account::ProviderImportAdapter.new(cash_sure).import_transaction(+ external_id: "trade_republic_event_evt_card_protected",+ amount: BigDecimal("15.00"),+ currency: "EUR",+ date: Date.parse("2026-08-01"),+ name: "Kept payment",+ source: "trade_republic",+ investment_activity_label: "Card payment"+ )+ entry.mark_user_modified!++ cash_account.update!(raw_timeline_payload: [ {+ id: "evt_card_protected",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "CARD_TRANSACTION",+ category: "POC_CREATED",+ status: "DECLINED",+ title: "Kept payment",+ detail: { amount: "15.00", currency: "EUR" }+ } ])++ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_card_protected")+ assert entry.reload.user_modified?+ end+private+ def create_linked_cash_account!+ cash_provider = @item.trade_republic_accounts.create!(+ name: "Cash",+ kind: "cash",+ trade_republic_account_id: "cash:DEPROC1",+ currency: "EUR",+ raw_timeline_payload: []+ )+ cash_sure = @family.accounts.create!(+ name: "Trade Republic Cash",+ balance: 0,+ cash_balance: 0,+ currency: "EUR",+ accountable: Depository.new+ )+ cash_provider.ensure_account_provider!(cash_sure)+ [ cash_provider.reload, cash_sure ]+ end++ def saveback_event+ {+ id: "evt_saveback",+ timestamp: "2026-09-02T08:11:30.780+0000",+ eventType: "SAVEBACK_AGGREGATE",+ category: "POC_CREATED",+ title: "STOXX Global Dividend 100 EUR (Dist)",+ subtitle: "Saveback",+ detail: {+ amount: "3.74",+ signed_amount: "-3.74",+ currency: "EUR",+ quantity: "0.09329",+ isin: "DE000A0F5UH1",+ name: "STOXX Global Dividend 100 EUR (Dist)"+ }+ }+ end++ def round_up_event+ {+ id: "evt_round_up",+ timestamp: "2026-09-02T08:11:30.780+0000",+ eventType: "SPARE_CHANGE_AGGREGATE",+ category: "POC_CREATED",+ title: "STOXX Global Dividend 100 EUR (Dist)",+ subtitle: "Round up",+ detail: {+ amount: "-0.40",+ signed_amount: "-0.40",+ currency: "EUR",+ quantity: "0.009977",+ isin: "DE000A0F5UH1",+ name: "STOXX Global Dividend 100 EUR (Dist)"+ }+ }+ end++ def savings_plan_invoice_event+ {+ id: "evt_savings_plan",+ timestamp: "2026-06-17T10:00:00Z",+ eventType: "SAVINGS_PLAN_INVOICE_CREATED",+ category: "orderExecution",+ title: "MSCI World",+ subtitle: "Savings plan",+ detail: {+ amount: "25.00",+ signed_amount: "-25.00",+ currency: "EUR",+ quantity: "0.25",+ isin: "IE00B4L5Y983",+ name: "MSCI World"+ }+ }+ end+def import_event(event)@tr_account.update!(raw_timeline_payload: [ event ])TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process@@ -307,6 +1227,6 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseenddef find_trade(external_id)- Entry.find_by(external_id: external_id)+ @account.entries.find_by(external_id: external_id)endenddiff --git a/test/models/trade_republic_account_holdings_processor_test.rb b/test/models/trade_republic_account_holdings_processor_test.rbindex 653f036a6c..a8628ea022 100644--- a/test/models/trade_republic_account_holdings_processor_test.rb+++ b/test/models/trade_republic_account_holdings_processor_test.rb@@ -117,20 +117,414 @@ class TradeRepublicAccountHoldingsProcessorTest < ActiveSupport::TestCaseendend+ test "resolves a holding to an exact exchange ticker and rematches this account only" do+ Security.stubs(:search_provider).returns([])++ isin = "DE000BASF111"+ isin_security = Security.create!(ticker: isin, name: "BASF ISIN", offline: false)+ other_account = @family.accounts.create!(+ name: "Other TR Account",+ balance: 0,+ cash_balance: 0,+ currency: "EUR",+ accountable: Investment.new+ )+ other_holding = other_account.holdings.create!(+ security: isin_security,+ date: Date.current,+ qty: 1,+ price: 40,+ amount: 40,+ currency: "EUR"+ )+ import_position(isin: isin, quantity: "5", price: "42.50")+ holding = @account.holdings.find_by!(security: isin_security)+ trade_entry = @account.entries.create!(+ name: "BASF buy",+ date: Date.current,+ amount: -100,+ currency: "EUR",+ entryable: Trade.new(security: isin_security, qty: 2, price: 50, currency: "EUR")+ )++ @tr_account.update!(raw_positions_payload: [+ position_payload(isin: isin, quantity: "5", price: "42.50", symbol: "BAS", exchange_slug: "XETR")+ ])+ TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload).process++ resolved = Security.find_by!(ticker: "BAS", exchange_operating_mic: "XETR")+ assert_equal false, resolved.offline?+ assert_equal resolved.id, holding.reload.security_id+ assert_equal resolved.id, trade_entry.reload.entryable.security_id+ assert_equal isin_security.id, other_holding.reload.security_id+ assert Security.exists?(id: isin_security.id)+ end++ test "existing exchange securities keep provider-managed offline states during position imports" do+ [+ [ "DE000BASF111", "BAS", "health_check_failed" ],+ [ "DE000BASF222", "BAS2", "provider_disabled" ]+ ].each do |isin, symbol, reason|+ security = Security.create!(+ ticker: symbol,+ exchange_operating_mic: "XETR",+ name: symbol,+ offline: true,+ offline_reason: reason+ )++ import_position(isin: isin, quantity: "5", price: "42.50", symbol: symbol, exchange_slug: "XETR")++ holding = @account.holdings.find_by!(security: security)+ assert_equal BigDecimal("42.50"), holding.price+ assert security.reload.offline?+ assert_equal reason, security.offline_reason+ end+ end++ test "a ticker rematch uses a new online security while the failed ISIN security stays offline" do+ Security.stubs(:search_provider).returns([])+ isin = "DE000BASF111"++ import_position(isin: isin, quantity: "5", price: "40")+ old_security = Security.find_by!(ticker: isin)+ old_security.update!(offline_reason: "health_check_failed")+ holding = @account.holdings.find_by!(security: old_security)++ import_position(isin: isin, quantity: "5", price: "42.50", symbol: "BAS", exchange_slug: "XETR")++ new_security = Security.find_by!(ticker: "BAS", exchange_operating_mic: "XETR")+ assert old_security.reload.offline?+ assert_equal "health_check_failed", old_security.offline_reason+ assert_not new_security.offline?+ assert_equal new_security.id, holding.reload.security_id+ assert_equal BigDecimal("42.50"), holding.price+ end++ test "a ticker rematch preserves an existing ticker security's offline state" do+ Security.stubs(:search_provider).returns([])+ isin = "DE000BASF111"++ import_position(isin: isin, quantity: "5", price: "40")+ old_security = Security.find_by!(ticker: isin)+ holding = @account.holdings.find_by!(security: old_security)+ ticker_security = Security.create!(+ ticker: "BAS",+ exchange_operating_mic: "XETR",+ name: "BASF",+ offline: true,+ offline_reason: "health_check_failed"+ )++ import_position(isin: isin, quantity: "5", price: "42.50", symbol: "BAS", exchange_slug: "XETR")++ assert ticker_security.reload.offline?+ assert_equal "health_check_failed", ticker_security.offline_reason+ assert_equal ticker_security.id, holding.reload.security_id+ assert_equal BigDecimal("42.50"), holding.price+ end++ test "provider confirmation preserves an existing exchange security's offline state" do+ security = Security.create!(+ ticker: "BAS.DE",+ exchange_operating_mic: "XETR",+ name: "BASF",+ offline: true,+ offline_reason: "health_check_failed"+ )+ Security.stubs(:search_provider).returns([+ Security.new(ticker: "BAS.DE", exchange_operating_mic: "XETR", name: "BASF")+ ])+ @tr_account.update!(raw_positions_payload: [+ position_payload(isin: "DE000BASF111", quantity: "5", price: "42.50", symbol: "BAS", exchange_slug: "XETR")+ ])+ processor = TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload)+ processor.stubs(:available_price_provider).returns("twelve_data")++ processor.process++ assert_equal security.id, @account.holdings.first.security_id+ assert security.reload.offline?+ assert_equal "health_check_failed", security.offline_reason+ assert_equal "twelve_data", security.price_provider+ end++ test "exchange security creation path preserves an existing offline security" do+ security = Security.create!(+ ticker: "BAS",+ exchange_operating_mic: "XETR",+ name: "BASF",+ offline: true,+ offline_reason: "health_check_failed"+ )+ processor = TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload)++ resolved = processor.send(+ :find_or_create_exchange_security!,+ ticker: "BAS",+ exchange_operating_mic: "XETR",+ name: "BASF",+ price_provider: "twelve_data"+ )++ assert_equal security.id, resolved.id+ assert security.reload.offline?+ assert_equal "health_check_failed", security.offline_reason+ assert_equal "twelve_data", security.price_provider+ end++ test "a concurrent exchange security insert does not abort the account sync" do+ winner = Security.create!(+ ticker: "BAS", exchange_operating_mic: "XETR", name: "BASF",+ offline: true, offline_reason: "health_check_failed"+ )+ duplicate = Security.new(ticker: "BAS", exchange_operating_mic: "XETR")+ duplicate.stubs(:valid?).returns(true) # Let the database unique index reject the insert.+ Security.stubs(:find_by_ticker_and_exchange).returns(nil, winner)+ Security.stubs(:find_or_initialize_by_ticker_and_exchange).returns(duplicate)+ Security.stubs(:search_provider).returns([])++ ActiveRecord::Base.transaction do+ import_position(isin: "DE000BASF111", quantity: "5", price: "42.50", symbol: "BAS", exchange_slug: "XETR")++ assert_equal winner.id, @account.holdings.first.security_id+ @account.update!(name: "Sync continued")+ end++ assert_equal "Sync continued", @account.reload.name+ assert_equal 1, Security.where(ticker: "BAS", exchange_operating_mic: "XETR").count+ assert winner.reload.offline?+ assert_equal "health_check_failed", winner.offline_reason+ end++ test "a concurrent provider-confirmed insert reuses the confirmed ticker" do+ winner = Security.create!(+ ticker: "BAS.DE", exchange_operating_mic: "XETR", name: "BASF",+ offline: true, offline_reason: "health_check_failed"+ )+ duplicate = Security.new(ticker: "BAS.DE", exchange_operating_mic: "XETR")+ duplicate.stubs(:valid?).returns(true) # Let the database unique index reject the insert.+ Security.stubs(:search_provider).returns([+ Security.new(ticker: "BAS.DE", exchange_operating_mic: "XETR", name: "BASF")+ ])+ Security.stubs(:find_or_initialize_by_ticker_and_exchange).returns(duplicate)+ processor = TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload)+ processor.stubs(:available_price_provider).returns("twelve_data")++ ActiveRecord::Base.transaction do+ @tr_account.update!(raw_positions_payload: [+ position_payload(isin: "DE000BASF111", quantity: "5", price: "42.50", symbol: "BAS", exchange_slug: "XETR")+ ])+ processor.process++ assert_equal winner.id, @account.holdings.first.security_id+ @account.update!(name: "Sync continued")+ end++ assert_equal "Sync continued", @account.reload.name+ assert_equal 1, Security.where(ticker: "BAS.DE", exchange_operating_mic: "XETR").count+ assert_not Security.exists?(ticker: "BAS", exchange_operating_mic: "XETR")+ assert winner.reload.offline?+ assert_equal "health_check_failed", winner.offline_reason+ assert_equal "twelve_data", winner.price_provider+ end++ test "a provider-confirmed ticker found by validation reuses the existing security" do+ winner = Security.create!(ticker: "BAS.DE", exchange_operating_mic: "XETR", name: "BASF")+ Security.stubs(:search_provider).returns([+ Security.new(ticker: "BAS.DE", exchange_operating_mic: "XETR", name: "BASF")+ ])+ Security.stubs(:find_or_initialize_by_ticker_and_exchange).returns(+ Security.new(ticker: "BAS.DE", exchange_operating_mic: "XETR")+ )+ processor = TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload)+ processor.stubs(:available_price_provider).returns("twelve_data")+ @tr_account.update!(raw_positions_payload: [+ position_payload(isin: "DE000BASF111", quantity: "5", price: "42.50", symbol: "BAS", exchange_slug: "XETR")+ ])++ processor.process++ assert_equal winner.id, @account.holdings.first.security_id+ assert_equal "twelve_data", winner.reload.price_provider+ assert_not Security.exists?(ticker: "BAS", exchange_operating_mic: "XETR")+ end++ test "rematch prefers exchange market values and merges cost basis on collision" do+ Security.stubs(:search_provider).returns([])++ isin = "DE000BASF111"+ isin_security = Security.create!(ticker: isin, name: "BASF ISIN", offline: true)+ prior_provider_security = Security.create!(ticker: "PRIOR_BAS", name: "Prior BASF", offline: true)+ exchange_security = Security.create!(+ ticker: "BAS",+ exchange_operating_mic: "XETR",+ name: "BASF",+ offline: false+ )++ isin_holding = @account.holdings.create!(+ security: isin_security,+ date: Date.current,+ qty: 3,+ price: 40,+ amount: 120,+ cost_basis: 38,+ currency: "EUR",+ external_id: "stale-isin-holding",+ provider_security_id: prior_provider_security.id,+ account_provider_id: @tr_account.account_provider.id+ )+ exchange_holding = @account.holdings.create!(+ security: exchange_security,+ date: Date.current,+ qty: 5,+ price: 42.5,+ amount: 212.5,+ currency: "EUR",+ external_id: "trade_republic_position_DEHOLD1_#{isin}_#{Date.current}",+ account_provider_id: @tr_account.account_provider.id+ )++ processor = TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload)+ assert_difference "DebugLogEntry.count", 1 do+ assert_nothing_raised do+ processor.send(:rematch_account_from_isin!, isin, exchange_security)+ end+ end++ assert_not Holding.exists?(isin_holding.id)+ assert Holding.exists?(exchange_holding.id)+ exchange_holding.reload+ assert_equal exchange_security.id, exchange_holding.security_id+ assert_equal BigDecimal("5"), exchange_holding.qty+ assert_equal BigDecimal("212.5"), exchange_holding.amount+ assert_equal BigDecimal("38"), exchange_holding.cost_basis+ assert_equal prior_provider_security.id, exchange_holding.provider_security_id+ end++ test "falls back to an offline ISIN security without a usable exchange symbol" do+ Security.stubs(:search_provider).returns([])++ import_position(isin: "LU3176111881", quantity: "3", price: "10")++ security = Security.find_by!(ticker: "LU3176111881")+ holding = @account.holdings.find_by!(security: security)++ assert security.offline?+ assert_equal "LU3176111881", holding.security.ticker+ end++ test "a concurrent offline ISIN insert does not abort the account sync" do+ isin = "LU3176111881"+ winner = Security.create!(ticker: isin, name: "Existing ISIN", offline: true)+ duplicate = Security.new(ticker: isin)+ duplicate.stubs(:valid?).returns(true) # Let the database unique index reject the insert.+ Security.stubs(:find_by).with(ticker: isin).returns(nil, winner)+ Security.stubs(:search_provider).returns([])++ ActiveRecord::Base.transaction do+ import_position(isin: isin, quantity: "3", price: "10")++ assert_equal winner.id, @account.holdings.first.security_id+ @account.update!(name: "Sync continued")+ end++ assert_equal "Sync continued", @account.reload.name+ assert_equal 1, Security.where(ticker: isin).count+ assert winner.reload.offline?+ end++ test "new offline ISIN securities record why they are offline" do+ Security.stubs(:search_provider).returns([])++ import_position(isin: "LU3176111881", quantity: "3", price: "10")++ security = Security.find_by!(ticker: "LU3176111881")+ assert security.offline?+ assert_equal "trade_republic_isin", security.offline_reason+ end++ test "an existing online ISIN security is reused without being taken offline" do+ Security.stubs(:search_provider).returns([])+ shared = Security.create!(ticker: "LU3176111881", name: "Shared ISIN", offline: false)++ import_position(isin: "LU3176111881", quantity: "3", price: "10")++ assert_equal shared.id, @account.holdings.first.security_id+ assert_not shared.reload.offline?+ assert_equal "Shared ISIN", shared.name+ end++ test "ISIN rematch runs once per processor and skips accounts without ISIN rows" do+ Security.stubs(:search_provider).returns([])+ Security.create!(ticker: "DE000BASF111", name: "BASF ISIN", offline: true)+ @tr_account.update!(raw_positions_payload: [+ position_payload(isin: "DE000BASF111", quantity: "5", price: "42.50", symbol: "BAS", exchange_slug: "XETR"),+ position_payload(isin: "DE000BASF111", quantity: "5", price: "42.50", symbol: "BAS", exchange_slug: "XETR")+ ])++ processor = TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload)+ processor.expects(:rematch_holdings_from_isin!).never+ processor.process+ end++ test "provider security lookups run before the account processor transaction" do+ baseline = ActiveRecord::Base.connection.open_transactions+ lookup_depths = []+ Security.stubs(:search_provider).with do |*|+ lookup_depths << ActiveRecord::Base.connection.open_transactions+ true+ end.returns([])+ Setting.stubs(:enabled_securities_providers).returns([ "twelve_data" ])+ Security.stubs(:provider_for).returns(Object.new)+ @tr_account.update!(+ current_balance: 425,+ raw_positions_payload: [+ position_payload(isin: "DE000BASF111", quantity: "10", price: "42.50", symbol: "BAS", exchange_slug: "XETR")+ ]+ )++ TradeRepublicAccount::Processor.new(@tr_account.reload).process++ assert_equal [ baseline ], lookup_depths+ assert_equal "BAS", @account.holdings.first.security.ticker+ end++ test "maps a Trade Republic Tradegate symbol to the Tradegate MIC" do+ Security.stubs(:search_provider).returns([])++ import_position(+ isin: "DE000TRAD123",+ quantity: "2",+ price: "20",+ symbol: "TRD",+ exchange_slug: "TDG"+ )++ security = @account.holdings.first.security+ assert_equal "TRD", security.ticker+ assert_equal "TGAT", security.exchange_operating_mic+ end+private- def import_position(isin:, quantity:, price:, average_cost: nil)- @tr_account.update!(raw_positions_payload: [ position_payload(isin:, quantity:, price:, average_cost:) ])+ def import_position(isin:, quantity:, price:, average_cost: nil, symbol: nil, exchange_slug: nil)+ @tr_account.update!(raw_positions_payload: [+ position_payload(isin:, quantity:, price:, average_cost:, symbol:, exchange_slug:)+ ])TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload).processend- def position_payload(isin:, quantity:, price:, average_cost: nil)+ def position_payload(isin:, quantity:, price:, average_cost: nil, symbol: nil, exchange_slug: nil){"isin" => isin,"name" => "Test Security","quantity" => quantity,"price" => price,- "average_cost" => average_cost+ "average_cost" => average_cost,+ "symbol" => symbol,+ "exchange_slug" => exchange_slug}.compactendenddiff --git a/test/models/trade_republic_client_test.rb b/test/models/trade_republic_client_test.rbindex 0e1fc50cd6..5f79e4219f 100644--- a/test/models/trade_republic_client_test.rb+++ b/test/models/trade_republic_client_test.rb@@ -73,11 +73,13 @@ class TradeRepublicClientTest < ActiveSupport::TestCasetest "normalizes current timeline event types to import categories" doassert_equal "orderExecution", Provider::TradeRepublicClient::EVENT_TYPE_CATEGORIES["TRADING_TRADE_EXECUTED"]assert_equal "orderExecution", Provider::TradeRepublicClient::EVENT_TYPE_CATEGORIES["TRADE_INVOICE"]+ assert_equal "orderExecution", Provider::TradeRepublicClient::EVENT_TYPE_CATEGORIES["SAVINGS_PLAN_INVOICE_CREATED"]assert_equal "DIVIDEND", Provider::TradeRepublicClient::EVENT_TYPE_CATEGORIES["DIVIDEND"]assert_equal "orderExecution", Provider::TradeRepublicClient::EVENT_TYPE_CATEGORIES["PRIVATE_MARKET_FUND_TRADE_EXECUTED"]assert_equal "POC_CREATED", Provider::TradeRepublicClient::EVENT_TYPE_CATEGORIES["CARD_ATM_WITHDRAWAL"]assert_equal "POC_CREATED", Provider::TradeRepublicClient::EVENT_TYPE_CATEGORIES["CARD_TRANSACTION"]assert_equal "POC_CREATED", Provider::TradeRepublicClient::EVENT_TYPE_CATEGORIES["CARD_CASH_BACK"]+ assert_nil Provider::TradeRepublicClient::EVENT_TYPE_CATEGORIES["TRADING_SAVINGSPLAN_EXECUTION_FAILED"]endtest "merges transaction and activity timelines without duplicate events" do@@ -96,21 +98,59 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseassert_empty warningsend- test "does not advance the cursor when timeline details are incomplete" do+ test "advances the list cursor when only trade details remain pending" do@client.define_singleton_method(:collect_timeline_topic) do |_websocket, topic:, **_|if topic == "timelineTransactions"- [ [ { "id" => "event-1", "timestamp" => "2026-08-02" } ], nil, [], true ]+ [ [ {+ "id" => "trade-1",+ "timestamp" => "2026-08-02",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "category" => "orderExecution",+ "detail" => { "amount" => -100.0 }+ } ], "trade-1", [], true ]else[ [], nil, [], true ]endend+ @client.define_singleton_method(:subscribe) do |_websocket, **_|+ raise Provider::TradeRepublicClient::MalformedResponse, "no budget"+ end- events, newest_id, warnings, complete = @client.send(:collect_all_timeline, Object.new, known_newest_event_id: nil, max_pages: 2)+ events, newest_id, warnings, complete, backfill_count = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: nil,+ max_pages: 2,+ enrich_events: []+ )- assert_equal [ "event-1" ], events.map { |event| event["id"] }- assert_nil newest_id- assert_empty warnings+ assert_equal [ "trade-1" ], events.map { |event| event["id"] }+ assert_equal "trade-1", newest_id+ assert complete+ assert_equal 0, backfill_count+ assert_includes warnings, "detail fetch failed for event trade-1"+ end++ test "does not mark timeline complete when pagination is truncated" do+ @client.define_singleton_method(:collect_timeline_topic) do |_websocket, topic:, **_|+ if topic == "timelineTransactions"+ [ [ { "id" => "event-1", "timestamp" => "2026-08-02" } ], "event-1", [ "timeline pagination truncated for timelineTransactions" ], false ]+ else+ [ [], nil, [], true ]+ end+ end++ _events, newest_id, warnings, complete, = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: nil,+ max_pages: 2,+ enrich_events: []+ )++ assert_equal "event-1", newest_idrefute complete+ assert_includes warnings, "timeline pagination truncated for timelineTransactions"endtest "recognizes QR login pending state" do@@ -195,7 +235,7 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseendtest "preserves an unpriced position for category visibility" do- @client.define_singleton_method(:subscribe) do |_websocket, **_payload|+ @client.define_singleton_method(:subscribe) do |_websocket, *_args, **_kwargs|raise Provider::TradeRepublicClient::ProviderUnavailableend@@ -217,7 +257,7 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseendtest "preserves a position when a ticker subscription times out" do- @client.define_singleton_method(:subscribe) do |_websocket, **_payload|+ @client.define_singleton_method(:subscribe) do |_websocket, *_args, **_kwargs|raise Provider::TradeRepublicClient::Timeout, "ticker did not answer"end@@ -234,6 +274,142 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseassert_equal [ "price unavailable for LU3176111881; position kept without valuation" ], warningsend+ test "falls back to average buy-in when private markets has no ticker" do+ @client.define_singleton_method(:subscribe) do |_websocket, *_args, **_kwargs|+ raise Provider::TradeRepublicClient::ProviderUnavailable+ end++ positions, warnings = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "privateMarkets", "positions" => [+ {+ "instrumentId" => "LU3176111881",+ "name" => "Private Equity",+ "netSize" => "1.01",+ "averageBuyIn" => "100.0"+ }+ ] }+ ]+ }, sec_acc_no: "0717713602")++ assert_empty warnings+ assert_equal "100.0", positions.first["price"]+ assert_equal "private_markets", positions.first["category"]+ end++ test "prefers homeInstrumentExchange ticker before the hardcoded exchange list" do+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ requested << payload+ case payload[:type]+ when "homeInstrumentExchange"+ { "exchangeId" => "XETR" }+ when "ticker"+ if payload[:id] == "DE000BASF111.XETR"+ { "last" => { "price" => "45.12" } }+ else+ raise Provider::TradeRepublicClient::ProviderUnavailable+ end+ else+ {}+ end+ end++ positions, warnings = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "stocksAndETFs", "positions" => [+ { "instrumentId" => "DE000BASF111", "name" => "BASF", "netSize" => "2" }+ ] }+ ]+ })++ assert_empty warnings+ assert_equal "45.12", positions.first["price"]+ assert requested.any? { |p| p[:type] == "homeInstrumentExchange" }+ assert requested.any? { |p| p[:type] == "ticker" && p[:id] == "DE000BASF111.XETR" }+ assert requested.none? { |p| p[:type] == "ticker" && p[:id].to_s.end_with?(".LSX") }+ end++ test "merges a privateMarketsPositions unit price when ticker feeds are empty" do+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ case payload[:type]+ when "privateMarketsPositions"+ {+ "positions" => [+ {+ "instrumentId" => "LU3176111881",+ "netSize" => "1.01",+ "unitPrice" => "108.50"+ }+ ]+ }+ else+ raise Provider::TradeRepublicClient::ProviderUnavailable+ end+ end++ positions, warnings = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "privateMarkets", "positions" => [+ {+ "instrumentId" => "LU3176111881",+ "name" => "Private Equity",+ "netSize" => "1.01",+ "averageBuyIn" => "100.0"+ }+ ] }+ ]+ }, sec_acc_no: "0717713602")++ assert_empty warnings+ assert_equal "108.50", positions.first["price"]+ end++ test "tolerates a rejected privateMarketsPositions subscription" do+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ if payload[:type] == "privateMarketsPositions"+ raise Provider::TradeRepublicClient::ProviderUnavailable, "no private markets sleeve"+ end++ raise Provider::TradeRepublicClient::ProviderUnavailable+ end++ positions, warnings = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "privateMarkets", "positions" => [+ {+ "instrumentId" => "LU3176111881",+ "name" => "Private Equity",+ "netSize" => "1.01",+ "averageBuyIn" => "100.0"+ }+ ] }+ ]+ }, sec_acc_no: "0717713602")++ assert_empty warnings+ assert_equal "100.0", positions.first["price"]+ end++ test "maps Google Pay inbound payments to deposits" do+ assert_equal "PAYMENT_RECEIVED",+ Provider::TradeRepublicClient::EVENT_TYPE_CATEGORIES["PAYMENT_INBOUND_GOOGLE_PAY"]+ assert_equal :financial, Provider::TradeRepublicTimelineEvent.classify(+ "eventType" => "PAYMENT_INBOUND_GOOGLE_PAY",+ "title" => "Cash in"+ )+ end++ test "ignores Legal documents timeline rows without an event type" do+ assert_equal :ignored, Provider::TradeRepublicTimelineEvent.classify(+ "title" => "Legal documents",+ "subtitle" => "Accepted"+ )+ end+test "marks a snapshot partial when malformed positions are skipped" do@client.expects(:position_price).never@@ -253,6 +429,153 @@ class TradeRepublicClientTest < ActiveSupport::TestCase], warningsend+ test "stores a real exchange symbol from the instrument subscription" do+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ case payload[:type]+ when "instrument"+ {+ "exchanges" => [+ { "slug" => "LSX", "symbolAtExchange" => "BAS", "active" => true },+ { "slug" => "XETR", "symbolAtExchange" => "BAS", "active" => true },+ { "slug" => "TIB", "symbolAtExchange" => "DE000BASF111", "active" => true }+ ]+ }+ when "ticker"+ { "last" => { "price" => "45.12" } }+ else+ {}+ end+ end++ positions, warnings = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "stocksAndETFs", "positions" => [+ { "instrumentId" => "DE000BASF111", "name" => "BASF", "netSize" => "10" }+ ] }+ ]+ })++ assert_empty warnings+ assert_equal "BAS", positions.first["symbol"]+ assert_equal "XETR", positions.first["exchange_slug"]+ assert_equal "45.12", positions.first["price"]+ end++ test "ignores instrument symbols that only echo the ISIN" do+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ case payload[:type]+ when "instrument"+ {+ "exchanges" => [+ { "slug" => "TIB", "symbolAtExchange" => "LU3176111881", "active" => true },+ { "slug" => "LSX", "symbolAtExchange" => "LU3176111881", "active" => true }+ ]+ }+ when "ticker"+ { "last" => { "price" => "12.00" } }+ else+ {}+ end+ end++ positions, _warnings = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "stocksAndETFs", "positions" => [+ { "instrumentId" => "LU3176111881", "name" => "ETF", "netSize" => "2" }+ ] }+ ]+ })++ assert_nil positions.first["symbol"]+ assert_nil positions.first["exchange_slug"]+ assert_equal "12.00", positions.first["price"]+ end++ test "keeps a position when the instrument subscription fails" do+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ if payload[:type] == "instrument"+ raise Provider::TradeRepublicClient::ProviderUnavailable, "instrument unavailable"+ end++ { "last" => { "price" => "99.50" } }+ end++ positions, warnings = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "stocksAndETFs", "positions" => [+ { "instrumentId" => "US0378331005", "name" => "Apple", "netSize" => "1" }+ ] }+ ]+ })++ assert_empty warnings+ assert_equal "US0378331005", positions.first["isin"]+ assert_equal "99.50", positions.first["price"]+ assert_nil positions.first["symbol"]+ end++ test "rate limits and transient errors from instrument lookups propagate" do+ [ Provider::TradeRepublicClient::RateLimited, Provider::TradeRepublicClient::TransientProviderError ].each do |error_class|+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ raise error_class, "slow down" if payload[:type] == "instrument"++ { "last" => { "price" => "99.50" } }+ end++ assert_raises(error_class) do+ @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "stocksAndETFs", "positions" => [+ { "instrumentId" => "US0378331005", "name" => "Apple", "netSize" => "1" }+ ] }+ ]+ })+ end+ end+ end++ test "reuses stored exchange symbols instead of re-subscribing to the instrument" do+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ requested << payload[:type]+ payload[:type] == "ticker" ? { "last" => { "price" => "45.12" } } : {}+ end++ positions, = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "stocksAndETFs", "positions" => [+ { "instrumentId" => "DE000BASF111", "name" => "BASF", "netSize" => "10" }+ ] }+ ]+ }, known_instrument_symbols: { "DE000BASF111" => { "symbol" => "BAS", "exchange_slug" => "XETR" } })++ assert_not_includes requested, "instrument"+ assert_equal "BAS", positions.first["symbol"]+ assert_equal "XETR", positions.first["exchange_slug"]+ end++ test "does not value listed positions at cost basis when no quote is available" do+ @client.define_singleton_method(:subscribe) do |_websocket, *_args, **_kwargs|+ raise Provider::TradeRepublicClient::ProviderUnavailable+ end++ positions, warnings = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "stocksAndETFs", "positions" => [+ { "instrumentId" => "US0378331005", "name" => "Apple", "netSize" => "1", "averageBuyIn" => "150.0" }+ ] }+ ]+ })++ assert_nil positions.first["price"]+ assert_equal [ "price unavailable for US0378331005; position kept without valuation" ], warnings+ end+test "resolves event type and preserves the signed timeline amount" do@client.define_singleton_method(:subscribe) do |_websocket, **_payload|{@@ -282,6 +605,403 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseassert_equal(-100.0, events.first.dig("detail", "signed_amount"))end+ test "normalize_event_detail parses Dutch share price and Kosten fees" do+ detail = @client.send(:normalize_event_detail, {+ "sections" => [+ { "title" => "Transactie", "data" => [+ { "title" => "Aandelen", "detail" => { "text" => "2" } },+ { "title" => "Aandelenkoers", "detail" => { "text" => "€511,96" } },+ { "title" => "Kosten", "detail" => { "text" => "€1,00" } },+ { "title" => "Totaal", "detail" => { "text" => "€1.024,92" } }+ ] },+ { "data" => [ { "detail" => { "action" => { "payload" => { "instrumentId" => "IE00B5BMR087" } } } } ] }+ ]+ }, item: { "title" => "Core S&P 500 USD (Acc)", "subtitle" => "Kopen" })++ assert_equal "IE00B5BMR087", detail["isin"]+ assert_equal "2.0", detail["quantity"]+ assert_equal "511.96", detail["price"]+ assert_equal "1.0", detail["fees"]+ assert_equal "1024.92", detail["amount"]+ end++ test "normalize_event_detail derives buy share price from total net of fees" do+ detail = @client.send(:normalize_event_detail, {+ "sections" => [+ { "title" => "Overview", "data" => [+ { "title" => "Shares", "detail" => { "text" => "2" } },+ { "title" => "Fee", "detail" => { "text" => "€1.00" } },+ { "title" => "Total", "detail" => { "text" => "€1,024.92" } }+ ] },+ { "data" => [ { "detail" => { "action" => { "payload" => { "instrumentId" => "IE00B5BMR087" } } } } ] }+ ]+ }, item: { "title" => "Core S&P 500", "subtitle" => "Buy" })++ assert_equal "511.96", detail["price"]+ assert_equal "1.0", detail["fees"]+ end++ test "normalize_event_detail derives sell share price from proceeds plus fees and taxes" do+ detail = @client.send(:normalize_event_detail, {+ "sections" => [+ { "title" => "Overview", "data" => [+ { "title" => "Shares", "detail" => { "text" => "2" } },+ { "title" => "Fee", "detail" => { "text" => "€1.00" } },+ { "title" => "Tax", "detail" => { "text" => "€0.50" } },+ { "title" => "Total", "detail" => { "text" => "€1,022.42" } }+ ] },+ { "data" => [ { "detail" => { "action" => { "payload" => { "instrumentId" => "IE00B5BMR087" } } } } ] }+ ]+ }, item: { "title" => "Core S&P 500", "subtitle" => "Sell" })++ # Sell cash = gross - fee - tax → 1022.42 = 2*511.96 - 1 - 0.50+ assert_equal "-2.0", detail["quantity"]+ assert_equal "511.96", detail["price"]+ assert_equal "1.0", detail["fees"]+ assert_equal "0.5", detail["taxes"]+ end++ test "trade_detail_needs_price_backfill detects complete trades without price" do+ assert Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => { "isin" => "IE00B5BMR087", "quantity" => "2", "amount" => "1024.92" }+ )+ refute Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => { "isin" => "IE00B5BMR087", "quantity" => "2", "price" => "511.96" }+ )+ end++ test "price backfill retries an unfixable trade at most once per day" do+ event = {+ "id" => "trade-1",+ "timestamp" => 2.days.ago.iso8601,+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => { "isin" => "IE00B5BMR087", "quantity" => "2" }+ }+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, **payload|+ requested << payload[:id]+ { "sections" => [] }+ end++ events, _warnings, backfill_count = @client.send(:enrich_timeline_details, Object.new, [], enrich_events: [ event ])++ assert_equal [ "trade-1" ], requested+ assert_equal 0, backfill_count+ stored = events.find { |candidate| candidate["id"] == "trade-1" }+ assert stored.dig("detail", Provider::TradeRepublicClient::PRICE_BACKFILL_ATTEMPTED_AT_KEY).present?+ refute Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(stored)+ refute Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(stored, 23.hours.from_now)+ assert Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(stored, 25.hours.from_now)+ end++ test "price backfill stops retrying once the trade is older than the retry window" do+ trade = {+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "timestamp" => 40.days.ago.iso8601,+ "detail" => { "isin" => "IE00B5BMR087", "quantity" => "2" }+ }+ attempted = trade.merge("detail" => trade["detail"].merge(+ Provider::TradeRepublicClient::PRICE_BACKFILL_ATTEMPTED_AT_KEY => 2.days.ago.iso8601+ ))++ assert Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(trade)+ refute Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(attempted)+ assert Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(+ attempted.merge("timestamp" => 29.days.ago.iso8601)+ )+ end++ test "symbol lookups retry daily until the window after the first attempt" do+ key = Provider::TradeRepublicClient::SYMBOL_LOOKUP_ATTEMPTED_AT_KEY+ first_key = Provider::TradeRepublicClient::SYMBOL_LOOKUP_FIRST_ATTEMPTED_AT_KEY+ event = ->(last, first) { { "detail" => { "isin" => "CA60255C8850", key => last&.iso8601, first_key => first&.iso8601 }.compact } }++ assert Provider::TradeRepublicClient.symbol_lookup_due?(event.call(nil, nil))+ refute Provider::TradeRepublicClient.symbol_lookup_due?(event.call(2.hours.ago, 5.days.ago))+ assert Provider::TradeRepublicClient.symbol_lookup_due?(event.call(25.hours.ago, 5.days.ago))+ refute Provider::TradeRepublicClient.symbol_lookup_due?(event.call(25.hours.ago, 31.days.ago))+ end++ test "enrich_trade_instrument_symbols reports ISINs without a usable symbol" do+ @client.define_singleton_method(:instrument_exchange_symbol) do |_websocket, isin|+ isin == "DE000BASF111" ? { symbol: "BAS", exchange_slug: "XETR" } : { symbol: isin, exchange_slug: "TIB" }+ end+ unresolved = []++ symbols = @client.send(+ :enrich_trade_instrument_symbols, Object.new, [],+ extra_isins: %w[DE000BASF111 CA60255C8850], unresolved: unresolved+ )++ assert_equal({ "symbol" => "BAS", "exchange_slug" => "XETR" }, symbols["DE000BASF111"])+ assert_equal [ "CA60255C8850" ], unresolved+ end++ test "price backfill counts only trades whose price was recovered" do+ event = {+ "id" => "trade-1",+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => { "isin" => "IE00B5BMR087", "quantity" => "2" }+ }+ @client.define_singleton_method(:subscribe) do |_websocket, **_payload|+ {+ "sections" => [+ { "title" => "Overview", "data" => [+ { "title" => "Shares", "detail" => { "text" => "2" } },+ { "title" => "Share price", "detail" => { "text" => "€511.96" } }+ ] },+ { "data" => [ { "detail" => { "action" => { "payload" => { "instrumentId" => "IE00B5BMR087" } } } } ] }+ ]+ }+ end++ events, _warnings, backfill_count = @client.send(:enrich_timeline_details, Object.new, [], enrich_events: [ event ])++ assert_equal 1, backfill_count+ assert_equal "511.96", events.first.dig("detail", "price")+ assert_nil events.first.dig("detail", Provider::TradeRepublicClient::PRICE_BACKFILL_ATTEMPTED_AT_KEY)+ end++ test "backfilled stored events do not move the list cursor" do+ @client.define_singleton_method(:collect_timeline_topic) do |_websocket, **_|+ [ [], nil, [], true ]+ end+ @client.define_singleton_method(:subscribe) do |_websocket, **_payload|+ {+ "sections" => [+ { "title" => "Overview", "data" => [+ { "title" => "Shares", "detail" => { "text" => "1" } },+ { "title" => "Total", "detail" => { "text" => "€10.00" } }+ ] },+ { "data" => [ { "detail" => { "action" => { "payload" => { "instrumentId" => "US0378331005" } } } } ] }+ ]+ }+ end++ events, newest_id, _warnings, complete, backfill_count = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: "newest-1",+ max_pages: 2,+ enrich_events: [ {+ "id" => "old-1",+ "timestamp" => "2024-06-17T10:00:00Z",+ "category" => "orderExecution",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "detail" => { "amount" => -10.0 }+ } ]+ )++ assert_equal [ "old-1" ], events.map { |event| event["id"] }+ assert_equal 1, backfill_count+ assert complete+ assert_nil newest_id+ end++ test "card and cash events do not consume timeline detail requests" do+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, **payload|+ requested << payload+ { "sections" => [] }+ end++ events, = @client.send(:resolve_details, Object.new, [+ {+ "id" => "card-1",+ "timestamp" => "2026-08-01T10:00:00Z",+ "eventType" => "CARD_TRANSACTION",+ "amount" => { "value" => -12.5, "currency" => "EUR" }+ },+ {+ "id" => "transfer-1",+ "timestamp" => "2026-08-01T11:00:00Z",+ "eventType" => "PAYMENT_INBOUND",+ "amount" => { "value" => 50.0, "currency" => "EUR" }+ }+ ], nil, [])++ assert_empty requested+ assert_equal [ "card-1", "transfer-1" ], events.map { |event| event["id"] }+ assert_equal(-12.5, events.first.dig("detail", "signed_amount"))+ end++ test "new dividends fetch details without changing the timeline amount" do+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, **payload|+ requested << payload[:id]+ {+ "sections" => [+ { "title" => "You received €4.30", "type" => "header", "data" => {+ "icon" => { "asset" => "logos/US0378331005/v2", "badge" => nil }+ } },+ { "title" => "Transaction", "data" => [+ { "title" => "Shares", "detail" => { "text" => "10.000000" } },+ { "title" => "Dividend per share", "detail" => { "text" => "0,51 €" } },+ { "title" => "Tax", "detail" => { "text" => "0,80 €" } },+ { "title" => "Total", "detail" => { "text" => "4,25 €" } }+ ] },+ { "title" => "Documents", "data" => [ { "title" => "Documents", "detail" => "01.08.2026" } ] }+ ]+ }+ end++ events, = @client.send(:resolve_details, Object.new, [+ {+ "id" => "dividend-1",+ "timestamp" => "2026-08-01T10:00:00Z",+ "title" => "Apple",+ "eventType" => "CREDIT",+ "category" => "DIVIDEND",+ "amount" => { "value" => 4.3, "currency" => "EUR" }+ }+ ], nil, [])++ detail = events.first["detail"]+ assert_equal [ "dividend-1" ], requested+ assert_equal "US0378331005", detail["isin"]+ assert_equal "10.0", detail["quantity"]+ assert_equal "0.51", detail["dividend_per_share"]+ assert_equal "0.8", detail["taxes"]+ assert_equal 4.3, detail["amount"]+ assert_nil detail["price"]+ end++ test "dividends that already have details are not fetched again" do+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, **payload|+ requested << payload[:id]+ { "sections" => [] }+ end+ stored = {+ "id" => "dividend-1",+ "timestamp" => "2026-08-01T10:00:00Z",+ "category" => "DIVIDEND",+ "detail" => { "isin" => "US0378331005", "amount" => 4.3 }+ }++ @client.send(:enrich_timeline_details, Object.new, [ stored ], enrich_events: [ stored.merge("detail" => nil) ])++ assert_empty requested+ end++ test "trade savings saveback and round-up events request timeline details" do+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, **payload|+ requested << payload[:id]+ {+ "sections" => [+ { "title" => "Overview", "data" => [+ { "title" => "Shares", "detail" => { "text" => "1.5" } },+ { "title" => "Total", "detail" => { "text" => "€100.00" } }+ ] },+ { "data" => [ { "detail" => { "action" => { "payload" => { "instrumentId" => "US0378331005" } } } } ] }+ ]+ }+ end++ items = [+ { "id" => "trade-1", "eventType" => "TRADING_TRADE_EXECUTED", "amount" => { "value" => -100.0 } },+ { "id" => "savings-1", "eventType" => "SAVINGS_PLAN_INVOICE_CREATED", "amount" => { "value" => -25.0 } },+ { "id" => "saveback-1", "eventType" => "SAVEBACK_AGGREGATE", "amount" => { "value" => -3.74 } },+ { "id" => "roundup-1", "eventType" => "SPARE_CHANGE_AGGREGATE", "amount" => { "value" => -0.40 } }+ ]++ events, = @client.send(:resolve_details, Object.new, items, nil, [])++ assert_equal %w[trade-1 savings-1 saveback-1 roundup-1], requested+ assert events.all? { |event| event.dig("detail", "isin") == "US0378331005" }+ end++ test "mixed pages prioritize reserved new details then backlog within the shared cap" do+ requested = []+ detail_response = {+ "sections" => [+ { "title" => "Overview", "data" => [+ { "title" => "Shares", "detail" => { "text" => "1" } },+ { "title" => "Total", "detail" => { "text" => "€10.00" } }+ ] },+ { "data" => [ { "detail" => { "action" => { "payload" => { "instrumentId" => "US0378331005" } } } } ] }+ ]+ }+ @client.define_singleton_method(:subscribe) do |_websocket, **payload|+ requested << payload[:id]+ detail_response+ end++ new_events = (Provider::TradeRepublicClient::MAX_TIMELINE_DETAILS_DELTA_RESERVED + 5).times.map do |index|+ {+ "id" => "new-#{index}",+ "timestamp" => "2026-09-0#{index % 9 + 1}T10:00:00Z",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "category" => "orderExecution",+ "detail" => { "amount" => -10.0 }+ }+ end+ backlog = 10.times.map do |index|+ {+ "id" => "old-#{index}",+ "timestamp" => "2025-01-0#{index % 9 + 1}T10:00:00Z",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "category" => "orderExecution",+ "detail" => { "amount" => -10.0 }+ }+ end++ events, warnings, backfill_count = @client.send(+ :enrich_timeline_details,+ Object.new,+ new_events,+ enrich_events: backlog+ )++ reserved = Provider::TradeRepublicClient::MAX_TIMELINE_DETAILS_DELTA_RESERVED+ assert_equal reserved.times.map { |index| "new-#{index}" } + backlog.map { |event| event["id"] } ++ (reserved...new_events.size).map { |index| "new-#{index}" }, requested+ assert_equal backlog.size, backfill_count+ assert_empty warnings+ assert events.any? { |event| event["id"] == "old-0" && event.dig("detail", "isin") == "US0378331005" }+ end++ test "failed detail attempts consume budget without blocking later candidates" do+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, **payload|+ requested << payload[:id]+ raise Provider::TradeRepublicClient::MalformedResponse, "bad" if payload[:id] == "fail-1"++ {+ "sections" => [+ { "title" => "Overview", "data" => [+ { "title" => "Shares", "detail" => { "text" => "1" } },+ { "title" => "Total", "detail" => { "text" => "€10.00" } }+ ] },+ { "data" => [ { "detail" => { "action" => { "payload" => { "instrumentId" => "US0378331005" } } } } ] }+ ]+ }+ end++ events, warnings, = @client.send(+ :enrich_timeline_details,+ Object.new,+ [+ { "id" => "fail-1", "eventType" => "TRADING_TRADE_EXECUTED", "category" => "orderExecution", "detail" => { "amount" => -1 } },+ { "id" => "ok-1", "eventType" => "TRADING_TRADE_EXECUTED", "category" => "orderExecution", "detail" => { "amount" => -1 } }+ ],+ enrich_events: []+ )++ assert_equal %w[fail-1 ok-1], requested+ assert_includes warnings, "detail fetch failed for event fail-1"+ assert_nil events.find { |event| event["id"] == "fail-1" }.dig("detail", "isin")+ assert_equal "US0378331005", events.find { |event| event["id"] == "ok-1" }.dig("detail", "isin")+ end+test "rejects an expired pending login state" dopending = {"process_id" => "process-1",@@ -402,4 +1122,397 @@ class TradeRepublicClientTest < ActiveSupport::TestCase@client.send(:raise_login_error, response)endend++ test "enriches stored savings-plan events with targeted timeline details" do+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, **payload|+ requested << payload+ {+ "sections" => [+ { "title" => "Overview", "data" => [+ { "title" => "Shares", "detail" => { "text" => "0.25" } },+ { "title" => "Total", "detail" => { "text" => "€25.00" } }+ ] },+ { "data" => [ { "detail" => { "action" => { "payload" => { "instrumentId" => "IE00B4L5Y983" } } } } ] }+ ]+ }+ end++ enriched, warnings = @client.send(+ :enrich_timeline_details,+ Object.new,+ [],+ enrich_events: [ {+ "id" => "savings-1",+ "timestamp" => "2026-06-17T10:00:00Z",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "title" => "MSCI World",+ "detail" => { "amount" => -25.0, "currency" => "EUR" }+ } ]+ )++ assert_empty warnings+ assert_equal 1, enriched.size+ assert_equal [ { type: "timelineDetailV2", id: "savings-1" } ], requested+ assert_equal "orderExecution", enriched.first["category"]+ assert_equal "IE00B4L5Y983", enriched.first.dig("detail", "isin")+ assert_equal BigDecimal("0.25"), BigDecimal(enriched.first.dig("detail", "quantity").to_s)+ end++ test "caps targeted detail enrichment and leaves leftovers for a later sync" do+ requested_ids = []+ @client.define_singleton_method(:subscribe) do |_websocket, **payload|+ requested_ids << payload[:id]+ {+ "sections" => [+ { "data" => [+ { "title" => "Shares", "detail" => { "text" => "1" } },+ { "detail" => { "action" => { "payload" => { "instrumentId" => "US0378331005" } } } }+ ] }+ ]+ }+ end++ max = Provider::TradeRepublicClient::MAX_TIMELINE_DETAILS+ events = (max + 3).times.map do |index|+ {+ "id" => "savings-#{index}",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "detail" => { "amount" => -10.0 }+ }+ end++ enriched, warnings = @client.send(:enrich_timeline_details, Object.new, [], enrich_events: events)++ assert_equal max, enriched.size+ assert_equal max, requested_ids.size+ assert_includes warnings.first, "detail enrichment truncated"+ end++ test "detail enrichment failures become warnings while transient errors still raise" do+ calls = 0+ @client.define_singleton_method(:subscribe) do |_websocket, **payload|+ calls += 1+ raise Provider::TradeRepublicClient::MalformedResponse, "bad detail" if payload[:id] == "fail-soft"+ raise Provider::TradeRepublicClient::Timeout, "timeout" if payload[:id] == "fail-hard"++ { "sections" => [] }+ end++ enriched, warnings = @client.send(+ :enrich_timeline_details,+ Object.new,+ [],+ enrich_events: [ { "id" => "fail-soft", "eventType" => "SAVINGS_PLAN_INVOICE_CREATED" } ]+ )++ assert_empty enriched+ assert_equal [ "detail fetch failed for event fail-soft" ], warnings++ assert_raises(Provider::TradeRepublicClient::Timeout) do+ @client.send(+ :enrich_timeline_details,+ Object.new,+ [],+ enrich_events: [ { "id" => "fail-hard", "eventType" => "SAVINGS_PLAN_INVOICE_CREATED" } ]+ )+ end+ end++ test "merge prefers richer detail fields over a later thin timeline copy" do+ merged = @client.send(+ :merge_enriched_events,+ [ {+ "id" => "savings-1",+ "category" => "orderExecution",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "detail" => { "amount" => -25.0, "isin" => "IE00B4L5Y983", "quantity" => "0.25" }+ } ],+ [ {+ "id" => "savings-1",+ "category" => "orderExecution",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "detail" => { "amount" => -25.0, "currency" => "EUR" }+ } ]+ )++ assert_equal 1, merged.size+ assert_equal "IE00B4L5Y983", merged.first.dig("detail", "isin")+ assert_equal "0.25", merged.first.dig("detail", "quantity")+ assert_equal "EUR", merged.first.dig("detail", "currency")+ end++ test "normalized events preserve lifecycle status deleted hidden and badge" do+ event = @client.send(+ :build_normalized_event,+ {+ "id" => "card-1",+ "timestamp" => "2026-09-02T10:00:00Z",+ "title" => "Coffee",+ "subtitle" => "Card payment",+ "eventType" => "CARD_TRANSACTION",+ "status" => "EXECUTED",+ "deleted" => false,+ "hidden" => true,+ "badge" => "Executed",+ "amount" => { "value" => -4.5, "currency" => "EUR" }+ },+ category: "POC_CREATED",+ detail: nil+ )++ assert_equal "EXECUTED", event["status"]+ assert_equal false, event["deleted"]+ assert_equal true, event["hidden"]+ assert_equal "Executed", event["badge"]+ assert_equal(-4.5, event.dig("detail", "amount"))+ end++ test "skeleton warnings only fire for truly unknown event types" do+ warnings = []+ @client.send(+ :build_skeleton_event,+ { "id" => "admin-1", "eventType" => "CARD_VERIFICATION", "title" => "Card verification" },+ warnings: warnings+ )+ assert_empty warnings++ @client.send(+ :build_skeleton_event,+ { "id" => "gap-1", "eventType" => "BRAND_NEW_MAPPING_GAP", "title" => "Mystery" },+ warnings: warnings+ )+ assert_equal [ "unsupported timeline event type BRAND_NEW_MAPPING_GAP" ], warnings+ end++ test "declined or deleted trade events are not treated as incomplete detail candidates" do+ declined = {+ "id" => "declined-1",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "category" => "orderExecution",+ "status" => "DECLINED",+ "detail" => { "amount" => -25.0 }+ }+ deleted = declined.merge("id" => "deleted-1", "status" => "EXECUTED", "deleted" => true)+ executed = declined.merge("id" => "ok-1", "status" => "EXECUTED", "deleted" => false)++ assert_not Provider::TradeRepublicClient.incomplete_trade_detail_event?(declined)+ assert_not Provider::TradeRepublicClient.incomplete_trade_detail_event?(deleted)+ assert Provider::TradeRepublicClient.incomplete_trade_detail_event?(executed)+ end++ test "detail enrichment skips ignored and non-importable events" do+ requested_ids = []+ @client.define_singleton_method(:subscribe) do |_websocket, **payload|+ requested_ids << payload[:id]+ { "sections" => [] }+ end++ events = [+ { "id" => "admin-1", "eventType" => "CARD_VERIFICATION", "category" => nil },+ {+ "id" => "declined-1",+ "eventType" => "CARD_TRANSACTION",+ "category" => "POC_CREATED",+ "status" => "DECLINED",+ "detail" => { "amount" => -12.0 }+ },+ {+ "id" => "trade-1",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "category" => "orderExecution",+ "detail" => { "amount" => -25.0 }+ }+ ]++ @client.send(:enrich_timeline_details, Object.new, events, enrich_events: [])++ assert_equal [ "trade-1" ], requested_ids+ end++ test "prefer_richer_event keeps newer lifecycle fields including false booleans" do+ previous = {+ "id" => "card-1",+ "category" => "POC_CREATED",+ "status" => "AUTHORIZED",+ "deleted" => true,+ "hidden" => true,+ "detail" => { "amount" => -10.0, "isin" => "US0378331005" }+ }+ incoming = {+ "id" => "card-1",+ "category" => "POC_CREATED",+ "status" => "EXECUTED",+ "deleted" => false,+ "hidden" => false,+ "detail" => { "amount" => -10.0, "currency" => "EUR" }+ }++ merged = @client.send(:prefer_richer_event, previous, incoming)++ assert_equal "EXECUTED", merged["status"]+ assert_equal false, merged["deleted"]+ assert_equal false, merged["hidden"]+ assert_equal "US0378331005", merged.dig("detail", "isin")+ assert_equal "EUR", merged.dig("detail", "currency")+ end++ test "enrich_trade_instrument_symbols stamps sold ISINs missing from portfolio" do+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ if payload[:type] == "instrument" && payload[:id] == "NL0000303709"+ {+ "exchanges" => [+ { "slug" => "XETR", "symbolAtExchange" => "ABN", "active" => true }+ ]+ }+ else+ {}+ end+ end++ events = [+ {+ "id" => "sell-abn",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "category" => "orderExecution",+ "detail" => {+ "isin" => "NL0000303709",+ "quantity" => "-10",+ "amount" => "150.00",+ "currency" => "EUR"+ }+ }+ ]++ symbols = @client.send(+ :enrich_trade_instrument_symbols,+ Object.new,+ events,+ known_symbols: { "DE000BASF111" => { "symbol" => "BAS", "exchange_slug" => "XETR" } }+ )++ assert_equal "ABN", events.first.dig("detail", "symbol")+ assert_equal "XETR", events.first.dig("detail", "exchange_slug")+ assert_equal "ABN", symbols.dig("NL0000303709", "symbol")+ assert_equal "BAS", symbols.dig("DE000BASF111", "symbol")+ end++ test "enrich_trade_instrument_symbols skips known symbols and respects the lookup cap" do+ looked_up = []+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ if payload[:type] == "instrument"+ looked_up << payload[:id]+ {+ "exchanges" => [+ { "slug" => "XETR", "symbolAtExchange" => "T#{looked_up.size}", "active" => true }+ ]+ }+ else+ {}+ end+ end++ known = { "HELD001" => { "symbol" => "HOLD", "exchange_slug" => "XETR" } }+ events = ([+ {+ "id" => "held-trade",+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => { "isin" => "HELD001", "quantity" => "1", "amount" => "10" }+ }+ ] + (1..3).map do |i|+ {+ "id" => "sold-#{i}",+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => { "isin" => "SOLD#{i}", "quantity" => "-1", "amount" => "10" }+ }+ end)++ stub_const = Provider::TradeRepublicClient.const_get(:MAX_INSTRUMENT_LOOKUPS)+ Provider::TradeRepublicClient.send(:remove_const, :MAX_INSTRUMENT_LOOKUPS)+ Provider::TradeRepublicClient.const_set(:MAX_INSTRUMENT_LOOKUPS, 2)++ begin+ symbols = @client.send(:enrich_trade_instrument_symbols, Object.new, events, known_symbols: known)+ ensure+ Provider::TradeRepublicClient.send(:remove_const, :MAX_INSTRUMENT_LOOKUPS)+ Provider::TradeRepublicClient.const_set(:MAX_INSTRUMENT_LOOKUPS, stub_const)+ end++ assert_equal [ "SOLD1", "SOLD2" ], looked_up+ refute_includes looked_up, "HELD001"+ assert_equal "HOLD", symbols.dig("HELD001", "symbol")+ assert_equal "T1", symbols.dig("SOLD1", "symbol")+ assert_equal "T2", symbols.dig("SOLD2", "symbol")+ assert_nil symbols["SOLD3"]+ assert_nil events.find { |e| e["id"] == "sold-3" }.dig("detail", "symbol")+ end++ test "enrich_trade_instrument_symbols ignores ISIN-echo symbols and failed lookups" do+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ case payload[:id]+ when "ECHO001"+ {+ "exchanges" => [+ { "slug" => "TIB", "symbolAtExchange" => "ECHO001", "active" => true }+ ]+ }+ when "FAIL001"+ raise Provider::TradeRepublicClient::ProviderUnavailable, "instrument unavailable"+ else+ {}+ end+ end++ events = [+ {+ "id" => "echo",+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => { "isin" => "ECHO001", "quantity" => "-1", "amount" => "10" }+ },+ {+ "id" => "fail",+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => { "isin" => "FAIL001", "quantity" => "-1", "amount" => "10" }+ }+ ]++ symbols = @client.send(:enrich_trade_instrument_symbols, Object.new, events, known_symbols: {})++ assert_empty symbols+ assert_nil events.first.dig("detail", "symbol")+ assert_nil events.last.dig("detail", "symbol")+ end++ test "enrich_trade_instrument_symbols looks up stored ISINs absent from the delta events" do+ @client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|+ payload = (args.first || kwargs).with_indifferent_access+ if payload[:type] == "instrument" && payload[:id] == "NL0000303709"+ {+ "exchanges" => [+ { "slug" => "XETR", "symbolAtExchange" => "ABN", "active" => true }+ ]+ }+ else+ {}+ end+ end++ symbols = @client.send(+ :enrich_trade_instrument_symbols,+ Object.new,+ [],+ known_symbols: {},+ extra_isins: [ "NL0000303709" ]+ )++ assert_equal "ABN", symbols.dig("NL0000303709", "symbol")+ assert_equal "XETR", symbols.dig("NL0000303709", "exchange_slug")+ endenddiff --git a/test/models/trade_republic_item_importer_test.rb b/test/models/trade_republic_item_importer_test.rbindex 0d485a3de7..fcaf1e55a9 100644--- a/test/models/trade_republic_item_importer_test.rb+++ b/test/models/trade_republic_item_importer_test.rb@@ -24,7 +24,8 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCaseresult = TradeRepublicItem::Importer.new(@item, provider: provider).import- assert_equal({ success: true }, result)+ assert_equal true, result[:success]+ assert_equal 0, result[:detail_backfill_count]account = @item.trade_republic_accounts.find_by(trade_republic_account_id: "DE9999")assert_not_nil account@@ -174,7 +175,7 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCaseTradeRepublicItem::Importer.new(@item, provider: provider).import- assert_equal 2, @item.reload.data_quality_summary[:events]+ assert_equal 1, @item.reload.data_quality_summary[:events]assert_equal 0, @item.data_quality_summary[:unknown_events]end@@ -326,6 +327,627 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCaseassert_equal [ "keep-event" ], account.raw_timeline_payload.map { |event| event["id"] }end+ test "cash timeline retains saveback and round up aggregates while excluding order executions" do+ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(client_result(+ "status" => "ok",+ "session_txt" => "# refreshed cookies",+ "account" => { "brokerage_account_id" => "DE-AGG", "currency" => "EUR" },+ "cash" => { "amount" => "10.00", "currency" => "EUR" },+ "positions" => [],+ "events" => [+ { "id" => "trade-1", "eventType" => "TRADING_TRADE_EXECUTED", "category" => "orderExecution" },+ { "id" => "saveback-1", "eventType" => "SAVEBACK_AGGREGATE", "category" => "POC_CREATED" },+ { "id" => "roundup-1", "eventType" => "SPARE_CHANGE_AGGREGATE", "category" => "POC_CREATED" }+ ],+ "newest_event_id" => "roundup-1",+ "warnings" => []+ ))++ TradeRepublicItem::Importer.new(@item, provider: provider).import++ portfolio = @item.trade_republic_accounts.find_by!(kind: "portfolio")+ cash = @item.trade_republic_accounts.find_by!(kind: "cash")++ assert_equal %w[trade-1 saveback-1 roundup-1], portfolio.raw_timeline_payload.map { |event| event["id"] }+ assert_equal %w[saveback-1 roundup-1], cash.raw_timeline_payload.map { |event| event["id"] }+ assert cash.raw_timeline_payload.none? { |event| event["category"] == "orderExecution" }+ end++ test "cash timeline cap counts only cash events" do+ events = 3.times.map do |index|+ { "id" => "trade-#{index}", "timestamp" => "2026-09-0#{index + 4}", "category" => "orderExecution" }+ end + 2.times.map do |index|+ { "id" => "card-#{index}", "timestamp" => "2026-09-0#{index + 1}", "category" => "POC_CREATED" }+ end+ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(client_result(+ "status" => "ok",+ "session_txt" => "# refreshed cookies",+ "account" => { "brokerage_account_id" => "DE-CAP", "currency" => "EUR" },+ "cash" => { "amount" => "10.00", "currency" => "EUR" },+ "positions" => [],+ "events" => events,+ "newest_event_id" => "trade-2",+ "warnings" => []+ ))++ original = TradeRepublicItem::Importer::MAX_TIMELINE_EVENTS+ TradeRepublicItem::Importer.send(:remove_const, :MAX_TIMELINE_EVENTS)+ TradeRepublicItem::Importer.const_set(:MAX_TIMELINE_EVENTS, 2)+ begin+ TradeRepublicItem::Importer.new(@item, provider: provider).import+ ensure+ TradeRepublicItem::Importer.send(:remove_const, :MAX_TIMELINE_EVENTS)+ TradeRepublicItem::Importer.const_set(:MAX_TIMELINE_EVENTS, original)+ end++ cash = @item.trade_republic_accounts.find_by!(kind: "cash")+ assert_equal %w[card-0 card-1], cash.raw_timeline_payload.map { |event| event["id"] }+ end++ test "passes stored exchange symbols so the client can skip instrument lookups" do+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-KNOWN",+ currency: "EUR",+ raw_positions_payload: [+ { "isin" => "DE000BASF111", "quantity" => "1", "symbol" => "BAS", "exchange_slug" => "XETR" },+ { "isin" => "LU3176111881", "quantity" => "1", "symbol" => "LU3176111881", "exchange_slug" => "TIB" }+ ]+ )+ provider = mock("trade_republic_provider")+ provider.expects(:sync).with(+ has_entries(known_instrument_symbols: { "DE000BASF111" => { "symbol" => "BAS", "exchange_slug" => "XETR" } })+ ).returns(client_result("status" => "session_expired"))++ assert_raises(Provider::TradeRepublicClient::AuthenticationRequired) do+ TradeRepublicItem::Importer.new(@item, provider: provider).import+ end+ end++ test "passes oldest incomplete trade-detail events for targeted enrichment" do+ incomplete_trade = {+ "id" => "trade-old",+ "timestamp" => "2026-05-01T10:00:00Z",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "category" => "orderExecution",+ "detail" => { "amount" => -100.0, "currency" => "EUR" }+ }+ incomplete_savings = {+ "id" => "savings-old",+ "timestamp" => "2026-06-17T10:00:00Z",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "detail" => { "amount" => -25.0, "currency" => "EUR" }+ }+ incomplete_saveback = {+ "id" => "saveback-old",+ "timestamp" => "2026-07-01T10:00:00Z",+ "eventType" => "SAVEBACK_AGGREGATE",+ "category" => "POC_CREATED",+ "detail" => { "amount" => -3.74, "currency" => "EUR" }+ }+ complete = {+ "id" => "savings-done",+ "timestamp" => "2026-08-01T10:00:00Z",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "category" => "orderExecution",+ "detail" => { "amount" => -25.0, "isin" => "IE00B4L5Y983", "quantity" => "0.25", "price" => "100.00" }+ }+ needs_price = {+ "id" => "trade-needs-price",+ "timestamp" => "2026-08-02T10:00:00Z",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "category" => "orderExecution",+ "detail" => { "amount" => -100.0, "isin" => "US0378331005", "quantity" => "1", "currency" => "EUR" }+ }+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-ENRICH",+ currency: "EUR",+ raw_timeline_payload: [ incomplete_saveback, complete, needs_price, incomplete_savings, incomplete_trade ]+ )++ provider = mock("trade_republic_provider")+ provider.expects(:sync).with { |args|+ enrich_ids = Array(args[:enrich_events]).map { |event| event["id"] || event[:id] }+ enrich_ids == %w[trade-old savings-old saveback-old trade-needs-price]+ }.returns(client_result(+ "status" => "ok",+ "session_txt" => "# refreshed cookies",+ "account" => { "brokerage_account_id" => "DE-ENRICH", "currency" => "EUR" },+ "cash" => { "amount" => "1", "currency" => "EUR" },+ "positions" => [],+ "events" => [],+ "newest_event_id" => "trade-needs-price",+ "timeline_pagination_complete" => true,+ "detail_backfill_count" => 0,+ "warnings" => []+ ))++ TradeRepublicItem::Importer.new(@item, provider: provider).import+ end++ test "advances newest_event_id when pagination completes with a detail backlog" do+ incomplete = {+ "id" => "savings-old",+ "timestamp" => "2026-06-17T10:00:00Z",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "detail" => { "amount" => -25.0, "currency" => "EUR" }+ }+ @item.update!(newest_event_id: "old-cursor")+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-CURSOR",+ currency: "EUR",+ raw_timeline_payload: [ incomplete ]+ )++ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(client_result(+ "status" => "partial",+ "domain_statuses" => {+ "account_metadata" => "success",+ "cash" => "success",+ "portfolio" => "success",+ "timeline" => "success",+ "instrument_metadata" => "success"+ },+ "account" => { "brokerage_account_id" => "DE-CURSOR", "currency" => "EUR" },+ "cash" => { "amount" => "1", "currency" => "EUR" },+ "positions" => [],+ "events" => [ incomplete ],+ "newest_event_id" => "new-cursor",+ "timeline_pagination_complete" => true,+ "detail_backfill_count" => 0,+ "warnings" => [ "detail fetch failed for event savings-old" ]+ ))++ result = TradeRepublicItem::Importer.new(@item, provider: provider).import++ assert_equal "new-cursor", @item.reload.newest_event_id+ assert_equal 0, result[:detail_backfill_count]+ assert_equal 1, @item.data_quality_summary[:pending_trade_details]+ end++ test "progressively enrichs incomplete portfolio events across syncs" do+ first = {+ "id" => "savings-1",+ "timestamp" => "2026-01-01T10:00:00Z",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "detail" => { "amount" => -25.0, "currency" => "EUR" }+ }+ second = {+ "id" => "savings-2",+ "timestamp" => "2026-02-01T10:00:00Z",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "detail" => { "amount" => -30.0, "currency" => "EUR" }+ }+ portfolio = @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-MULTI",+ currency: "EUR",+ raw_timeline_payload: [ first, second ]+ )++ enriched_first = first.merge(+ "category" => "orderExecution",+ "detail" => first["detail"].merge("isin" => "IE00B4L5Y983", "quantity" => "0.25")+ )++ provider = mock("trade_republic_provider")+ provider.expects(:sync).twice.returns(+ client_result(+ "status" => "ok",+ "session_txt" => "# refreshed cookies",+ "account" => { "brokerage_account_id" => "DE-MULTI", "currency" => "EUR" },+ "cash" => { "amount" => "1", "currency" => "EUR" },+ "positions" => [],+ "events" => [ enriched_first ],+ "newest_event_id" => "cursor-1",+ "timeline_pagination_complete" => true,+ "detail_backfill_count" => 1,+ "warnings" => []+ ),+ client_result(+ "status" => "ok",+ "session_txt" => "# refreshed cookies",+ "account" => { "brokerage_account_id" => "DE-MULTI", "currency" => "EUR" },+ "cash" => { "amount" => "1", "currency" => "EUR" },+ "positions" => [],+ "events" => [ second.merge(+ "category" => "orderExecution",+ "detail" => second["detail"].merge("isin" => "US0378331005", "quantity" => "0.10")+ ) ],+ "newest_event_id" => "cursor-1",+ "timeline_pagination_complete" => true,+ "detail_backfill_count" => 1,+ "warnings" => []+ )+ )++ first_result = TradeRepublicItem::Importer.new(@item, provider: provider).import+ assert_equal 1, first_result[:detail_backfill_count]+ stored_after_first = portfolio.reload.raw_timeline_payload.index_by { |event| event["id"] }+ assert_equal "IE00B4L5Y983", stored_after_first["savings-1"].dig("detail", "isin")+ assert_nil stored_after_first["savings-2"].dig("detail", "isin")+ assert_equal 1, @item.data_quality_summary[:pending_trade_details]++ second_result = TradeRepublicItem::Importer.new(@item, provider: provider).import+ assert_equal 1, second_result[:detail_backfill_count]+ stored_after_second = portfolio.reload.raw_timeline_payload.index_by { |event| event["id"] }+ assert_equal "IE00B4L5Y983", stored_after_second["savings-1"].dig("detail", "isin")+ assert_equal "0.25", stored_after_second["savings-1"].dig("detail", "quantity")+ assert_equal "US0378331005", stored_after_second["savings-2"].dig("detail", "isin")+ assert_equal 0, @item.data_quality_summary[:pending_trade_details]+ end++ test "backfills an amount-only savings-plan event and removes the stale cash copy" do+ incomplete = {+ "id" => "savings-1",+ "timestamp" => "2026-06-17T10:00:00Z",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "detail" => { "amount" => -25.0, "currency" => "EUR" }+ }+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-BACKFILL",+ currency: "EUR",+ raw_timeline_payload: [ incomplete ]+ )+ cash = @item.trade_republic_accounts.create!(+ kind: "cash",+ name: "Cash",+ trade_republic_account_id: "cash:DE-BACKFILL",+ currency: "EUR",+ raw_timeline_payload: [ incomplete ]+ )++ enriched = incomplete.merge(+ "category" => "orderExecution",+ "detail" => {+ "amount" => -25.0,+ "currency" => "EUR",+ "isin" => "IE00B4L5Y983",+ "quantity" => "0.25",+ "name" => "MSCI World"+ }+ )++ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(client_result(+ "status" => "ok",+ "session_txt" => "# refreshed cookies",+ "account" => { "brokerage_account_id" => "DE-BACKFILL", "currency" => "EUR" },+ "cash" => { "amount" => "10.00", "currency" => "EUR" },+ "positions" => [],+ "events" => [ enriched ],+ "newest_event_id" => "savings-1",+ "warnings" => []+ ))++ TradeRepublicItem::Importer.new(@item, provider: provider).import++ portfolio = @item.trade_republic_accounts.find_by!(kind: "portfolio")+ stored = portfolio.reload.raw_timeline_payload.find { |event| event["id"] == "savings-1" }++ assert_equal "orderExecution", stored["category"]+ assert_equal "IE00B4L5Y983", stored.dig("detail", "isin")+ assert_equal "0.25", stored.dig("detail", "quantity")+ assert cash.reload.raw_timeline_payload.none? { |event| event["id"] == "savings-1" }+ end++ test "preserves enriched savings-plan details when a thin timeline copy reappears" do+ rich = {+ "id" => "savings-1",+ "timestamp" => "2026-06-17T10:00:00Z",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "category" => "orderExecution",+ "detail" => {+ "amount" => -25.0,+ "currency" => "EUR",+ "isin" => "IE00B4L5Y983",+ "quantity" => "0.25"+ }+ }+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-RICH",+ currency: "EUR",+ raw_timeline_payload: [ rich ]+ )++ thin = {+ "id" => "savings-1",+ "timestamp" => "2026-06-17T10:00:00Z",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "category" => "orderExecution",+ "detail" => { "amount" => -25.0, "currency" => "EUR" }+ }++ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(client_result(+ "status" => "ok",+ "session_txt" => "# refreshed cookies",+ "account" => { "brokerage_account_id" => "DE-RICH", "currency" => "EUR" },+ "cash" => { "amount" => "1", "currency" => "EUR" },+ "positions" => [],+ "events" => [ thin ],+ "newest_event_id" => "savings-1",+ "warnings" => []+ ))++ TradeRepublicItem::Importer.new(@item, provider: provider).import++ stored = @item.trade_republic_accounts.find_by!(kind: "portfolio").reload.raw_timeline_payload.first+ assert_equal "IE00B4L5Y983", stored.dig("detail", "isin")+ assert_equal "0.25", stored.dig("detail", "quantity")+ assert_equal "EUR", stored.dig("detail", "currency")+ end++ test "prefer_richer_timeline_event merges newer lifecycle fields including false flags" do+ importer = TradeRepublicItem::Importer.new(@item, provider: mock("provider"))+ previous = {+ id: "card-1",+ category: "POC_CREATED",+ status: "AUTHORIZED",+ deleted: true,+ hidden: true,+ detail: { amount: -10.0, isin: "US0378331005" }+ }+ incoming = {+ id: "card-1",+ category: "POC_CREATED",+ status: "EXECUTED",+ deleted: false,+ hidden: false,+ detail: { amount: -10.0, currency: "EUR" }+ }++ merged = importer.send(:prefer_richer_timeline_event, previous, incoming)++ assert_equal "EXECUTED", merged[:status]+ assert_equal false, merged[:deleted]+ assert_equal false, merged[:hidden]+ assert_equal "US0378331005", merged.dig(:detail, :isin)+ assert_equal "EUR", merged.dig(:detail, :currency)+ end++ test "events needing detail enrichment exclude non-importable lifecycle events" do+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-ENRICH",+ currency: "EUR",+ raw_timeline_payload: [+ {+ "id" => "declined-savings",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "category" => "orderExecution",+ "status" => "DECLINED",+ "detail" => { "amount" => -25.0 }+ },+ {+ "id" => "admin-verify",+ "eventType" => "CARD_VERIFICATION"+ },+ {+ "id" => "incomplete-ok",+ "eventType" => "SAVINGS_PLAN_INVOICE_CREATED",+ "category" => "orderExecution",+ "status" => "EXECUTED",+ "detail" => { "amount" => -25.0 }+ }+ ]+ )++ enrich_ids = TradeRepublicItem::Importer.new(@item, provider: mock("provider"))+ .send(:events_needing_detail_enrichment)+ .map { |event| event["id"] || event[:id] }++ assert_equal [ "incomplete-ok" ], enrich_ids+ end++ test "events needing detail enrichment include complete trades missing share price" do+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-PRICE",+ currency: "EUR",+ raw_timeline_payload: [+ {+ "id" => "needs-price",+ "timestamp" => "2024-03-28T10:00:00Z",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "category" => "orderExecution",+ "detail" => {+ "isin" => "IE00B5BMR087",+ "quantity" => "2",+ "amount" => "1024.92",+ "currency" => "EUR"+ }+ },+ {+ "id" => "has-price",+ "timestamp" => "2024-03-29T10:00:00Z",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "category" => "orderExecution",+ "detail" => {+ "isin" => "IE00B5BMR087",+ "quantity" => "1",+ "amount" => "500.00",+ "price" => "500.00",+ "currency" => "EUR"+ }+ }+ ]+ )++ enrich_ids = TradeRepublicItem::Importer.new(@item, provider: mock("provider"))+ .send(:events_needing_detail_enrichment)+ .map { |event| event["id"] || event[:id] }++ assert_equal [ "needs-price" ], enrich_ids+ end++ test "apply_instrument_symbols stamps merged timeline events that lacked a ticker" do+ importer = TradeRepublicItem::Importer.new(@item, provider: mock("provider"))+ events = [+ {+ id: "old-sell",+ category: "orderExecution",+ detail: { isin: "NL0000303709", quantity: "-5", amount: "80.00" }+ }.with_indifferent_access,+ {+ id: "already-resolved",+ category: "orderExecution",+ detail: { isin: "DE000BASF111", symbol: "BAS", exchange_slug: "XETR", quantity: "1" }+ }.with_indifferent_access+ ]++ importer.send(:apply_instrument_symbols!, events, {+ "NL0000303709" => { "symbol" => "ABN", "exchange_slug" => "XETR" },+ "DE000BASF111" => { "symbol" => "SHOULD_NOT_OVERRIDE", "exchange_slug" => "XETR" }+ })++ assert_equal "ABN", events.first.dig(:detail, :symbol)+ assert_equal "XETR", events.first.dig(:detail, :exchange_slug)+ assert_equal "BAS", events.last.dig(:detail, :symbol)+ end++ test "import applies instrument_symbols to previously stored trades without symbols" do+ portfolio = @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-SYMBOLS",+ currency: "EUR",+ raw_timeline_payload: [+ {+ "id" => "historical-sell",+ "timestamp" => "2025-01-01T10:00:00Z",+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => {+ "isin" => "NL0000303709",+ "quantity" => "-10",+ "amount" => "150.00",+ "currency" => "EUR"+ }+ }+ ]+ )++ provider = mock("trade_republic_provider")+ provider.expects(:sync).with(+ has_entries(symbol_lookup_isins: [ "NL0000303709" ])+ ).returns(client_result(+ "status" => "ok",+ "session_txt" => "# cookies",+ "account" => { "brokerage_account_id" => "DE-SYMBOLS", "currency" => "EUR" },+ "cash" => { "amount" => "100.00", "currency" => "EUR" },+ "positions" => [],+ "events" => [],+ "instrument_symbols" => {+ "NL0000303709" => { "symbol" => "ABN", "exchange_slug" => "XETR" }+ },+ "newest_event_id" => "historical-sell",+ "timeline_pagination_complete" => true,+ "warnings" => []+ ))++ TradeRepublicItem::Importer.new(@item, provider: provider).import++ stored = portfolio.reload.raw_timeline_payload.first+ assert_equal "ABN", stored.dig("detail", "symbol") || stored.dig("detail", :symbol)+ assert_equal "XETR", stored.dig("detail", "exchange_slug") || stored.dig("detail", :exchange_slug)+ end++ test "unresolved symbol lookups are stamped and not retried within a day" do+ portfolio = @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-UNRESOLVED",+ currency: "EUR",+ raw_timeline_payload: [+ {+ "id" => "historical-sell",+ "timestamp" => "2025-01-01T10:00:00Z",+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => { "isin" => "CA60255C8850", "quantity" => "-10", "amount" => "150.00", "currency" => "EUR" }+ }+ ]+ )+ sync_result = client_result(+ "status" => "ok",+ "session_txt" => "# cookies",+ "account" => { "brokerage_account_id" => "DE-UNRESOLVED", "currency" => "EUR" },+ "cash" => { "amount" => "100.00", "currency" => "EUR" },+ "positions" => [],+ "events" => [],+ "instrument_symbols" => {},+ "unresolved_symbol_isins" => [ "CA60255C8850" ],+ "newest_event_id" => "historical-sell",+ "timeline_pagination_complete" => true,+ "warnings" => []+ )+ provider = mock("trade_republic_provider")+ provider.expects(:sync).with(has_entries(symbol_lookup_isins: [ "CA60255C8850" ])).returns(sync_result)+ provider.expects(:sync).with(has_entries(symbol_lookup_isins: [])).returns(sync_result)++ TradeRepublicItem::Importer.new(@item, provider: provider).import+ detail = portfolio.reload.raw_timeline_payload.first["detail"]+ first_attempt = detail[Provider::TradeRepublicClient::SYMBOL_LOOKUP_FIRST_ATTEMPTED_AT_KEY]+ assert first_attempt.present?+ assert detail[Provider::TradeRepublicClient::SYMBOL_LOOKUP_ATTEMPTED_AT_KEY].present?++ travel 1.hour do+ TradeRepublicItem::Importer.new(@item.reload, provider: provider).import+ end+ assert_equal first_attempt,+ portfolio.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+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-LOOKUP",+ currency: "EUR",+ raw_timeline_payload: [+ {+ "id" => "need-lookup",+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => { "isin" => "NL0000303709", "quantity" => "-1", "amount" => "10" }+ },+ {+ "id" => "already-have",+ "category" => "orderExecution",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "detail" => {+ "isin" => "DE000BASF111",+ "symbol" => "BAS",+ "exchange_slug" => "XETR",+ "quantity" => "1",+ "amount" => "10"+ }+ }+ ]+ )++ isins = TradeRepublicItem::Importer.new(@item, provider: mock("provider"))+ .send(:isins_needing_symbol_lookup)++ assert_equal [ "NL0000303709" ], isins+ end+privatedef client_result(data)diff --git a/test/models/trade_republic_item_test.rb b/test/models/trade_republic_item_test.rbindex 9f334964ed..c3d2a94bf4 100644--- a/test/models/trade_republic_item_test.rb+++ b/test/models/trade_republic_item_test.rb@@ -89,4 +89,109 @@ class TradeRepublicItemTest < ActiveSupport::TestCaseassert_match(/1 linked, 1 need setup/i, item.reload.sync_status_summary)end++ test "data_quality_summary dedupes portfolio and cash timeline events" do+ item = trade_republic_items(:configured_item)+ item.trade_republic_accounts.destroy_all++ shared = {+ "id" => "evt_shared",+ "eventType" => "CARD_TRANSACTION",+ "category" => "POC_CREATED",+ "status" => "EXECUTED"+ }+ cash_only = {+ "id" => "evt_cash_only",+ "eventType" => "PAYMENT_INBOUND",+ "category" => "PAYMENT_RECEIVED"+ }+ admin = {+ "id" => "evt_admin",+ "eventType" => "CARD_VERIFICATION",+ "title" => "Card verification"+ }+ legal_docs = {+ "id" => "evt_legal",+ "title" => "Legal documents",+ "subtitle" => "Accepted"+ }+ order_created = {+ "id" => "evt_order_created",+ "eventType" => "TRADING_ORDER_CREATED",+ "title" => "SanDisk",+ "subtitle" => "Limit buy created"+ }+ mapping_gap = {+ "id" => "evt_gap",+ "eventType" => "BRAND_NEW_MAPPING_GAP",+ "title" => "Mystery"+ }++ item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-DQ-P",+ currency: "EUR",+ raw_timeline_payload: [ shared, admin, legal_docs, order_created, mapping_gap ]+ )+ item.trade_republic_accounts.create!(+ kind: "cash",+ name: "Cash",+ trade_republic_account_id: "DE-DQ-C",+ currency: "EUR",+ raw_timeline_payload: [ shared, cash_only, admin ]+ )++ summary = item.data_quality_summary++ assert_equal 6, summary[:events]+ assert_equal 1, summary[:unknown_events]+ end++ test "process_accounts processes portfolio before cash even when cash was created first" do+ item = trade_republic_items(:configured_item)+ item.trade_republic_accounts.destroy_all++ cash = item.trade_republic_accounts.create!(+ kind: "cash",+ name: "Cash First",+ trade_republic_account_id: "DE-ORD-C",+ currency: "EUR"+ )+ portfolio = item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio Second",+ trade_republic_account_id: "DE-ORD-P",+ currency: "EUR"+ )++ cash_sure = item.family.accounts.create!(+ name: "TR Cash Order",+ balance: 0,+ cash_balance: 0,+ currency: "EUR",+ accountable: Depository.new+ )+ portfolio_sure = item.family.accounts.create!(+ name: "TR Portfolio Order",+ balance: 0,+ cash_balance: 0,+ currency: "EUR",+ accountable: Investment.new+ )+ cash.ensure_account_provider!(cash_sure)+ portfolio.ensure_account_provider!(portfolio_sure)++ processed_kinds = []+ fake_processor = Object.new+ fake_processor.define_singleton_method(:process) { true }+ TradeRepublicAccount::Processor.stubs(:new).with { |tr_account|+ processed_kinds << tr_account.kind+ true+ }.returns(fake_processor)++ item.process_accounts++ assert_equal %w[portfolio cash], processed_kinds+ endend