The personal finance app for everyone (by everyone)
Ruby
Import Trade Republic transfer payment references as transaction notes (#4833)
Chris Werner Rau12783085d3ff
diff --git a/app/models/provider/trade_republic_client.rb b/app/models/provider/trade_republic_client.rbindex b73a180cc8..2d95f01341 100644--- a/app/models/provider/trade_republic_client.rb+++ b/app/models/provider/trade_republic_client.rb@@ -145,9 +145,30 @@ class Provider::TradeRepublicClient# Stored trades whose detail is still incomplete after a fetch; the backlog# retries the least recently attempted first.DETAIL_BACKFILL_ATTEMPTED_AT_KEY = "detail_backfill_attempted_at"+ # Transfers and direct debits can carry a payment reference. The timeline+ # list never includes it; only timelineDetailV2 does, as the text of a+ # section of type "note". Card payments and the other cash movements have+ # none, so they don't spend the detail budget.+ CASH_NOTE_EVENT_TYPES = %w[+ BANK_TRANSACTION_INCOMING+ INCOMING_TRANSFER+ INCOMING_TRANSFER_DELEGATION+ PAYMENT_INBOUND+ PAYMENT_INBOUND_SEPA_DIRECT_DEBIT+ BANK_TRANSACTION_OUTGOING+ BANK_TRANSACTION_OUTGOING_DIRECT_DEBIT+ BANK_TRANSACTION_OUTGOING_SCHEDULED+ OUTGOING_TRANSFER+ OUTGOING_TRANSFER_DELEGATION+ PAYMENT_OUTBOUND+ ].freeze+ NOTE_SECTION_TYPE = "note"+ # Set once the detail of a transfer was read, with or without a note, so+ # transfers without a note are not fetched again.+ NOTE_CHECKED_AT_KEY = "note_checked_at"RETRY_MARKER_KEYS = [PRICE_BACKFILL_ATTEMPTED_AT_KEY, SYMBOL_LOOKUP_ATTEMPTED_AT_KEY, SYMBOL_LOOKUP_FIRST_ATTEMPTED_AT_KEY,- DETAIL_BACKFILL_ATTEMPTED_AT_KEY+ DETAIL_BACKFILL_ATTEMPTED_AT_KEY, NOTE_CHECKED_AT_KEY].freeze# Cap instrument lookups for sold / historical trade ISINs that are absent# from the current portfolio snapshot.@@ -361,7 +382,7 @@ class Provider::TradeRepublicClientendend- def sync(session_txt:, known_newest_event_id: nil, timeline_cursors: {}, timeline_max_pages: MAX_TIMELINE_PAGES, enrich_events: [], symbol_lookup_isins: [], known_instrument_symbols: {})+ def sync(session_txt:, known_newest_event_id: nil, timeline_cursors: {}, timeline_max_pages: MAX_TIMELINE_PAGES, enrich_events: [], note_read_event_ids: [], symbol_lookup_isins: [], known_instrument_symbols: {})raise ConfigurationError, "session_txt is required" if session_txt.blank?interrupted_backfills = {}@@ -372,6 +393,7 @@ class Provider::TradeRepublicClienttimeline_cursors: timeline_cursors,timeline_max_pages: timeline_max_pages,enrich_events: enrich_events,+ note_read_event_ids: note_read_event_ids,symbol_lookup_isins: symbol_lookup_isins,known_instrument_symbols: known_instrument_symbols,interrupted_backfills: interrupted_backfills@@ -382,7 +404,7 @@ class Provider::TradeRepublicClientendend- def sync_once(session_txt:, known_newest_event_id:, timeline_max_pages:, timeline_cursors: {}, enrich_events: [], symbol_lookup_isins: [], known_instrument_symbols: {}, interrupted_backfills: {})+ def sync_once(session_txt:, known_newest_event_id:, timeline_max_pages:, timeline_cursors: {}, enrich_events: [], note_read_event_ids: [], symbol_lookup_isins: [], known_instrument_symbols: {}, interrupted_backfills: {})session = new_session(session_blob: session_txt)account_response = session.get("/api/v2/auth/account")if [ 401, 403 ].include?(account_response.code.to_i) && !waf_error?(account_response)@@ -449,6 +471,7 @@ class Provider::TradeRepublicClientknown_newest_event_id: known_newest_event_id,max_pages: timeline_max_pages.to_i,enrich_events: enrich_events,+ note_read_event_ids: note_read_event_ids,timeline_cursors: timeline_cursors,interrupted_backfills: interrupted_backfills)@@ -555,6 +578,26 @@ class Provider::TradeRepublicClient!(detail.is_a?(Hash) && detail.stringify_keys["isin"].present?)end+ # An importable transfer or direct debit whose detail was never read for+ # its note.+ def cash_note_pending?(event)+ return false unless event.is_a?(Hash)+ return false unless CASH_NOTE_EVENT_TYPES.include?(event.stringify_keys["eventType"].to_s)++ Provider::TradeRepublicTimelineEvent.importable?(event.stringify_keys) && !cash_note_read?(event)+ end++ # A transfer or direct debit whose detail was read for its note, with or+ # without a result.+ def cash_note_read?(event)+ return false unless event.is_a?(Hash)++ item = event.stringify_keys+ detail = item["detail"]+ CASH_NOTE_EVENT_TYPES.include?(item["eventType"].to_s) &&+ detail.is_a?(Hash) && detail.stringify_keys.values_at("note", NOTE_CHECKED_AT_KEY).any?(&:present?)+ end+# Complete trades (isin + quantity) without a price read from the detail:# the price is missing, or was derived from the rounded total, usually# because the trade was stored before its price rows were parsed.@@ -577,10 +620,12 @@ class Provider::TradeRepublicClient# first, oldest first, then the least recently attempted, so events that# stay incomplete can't hold the budget on every sync. Price backfills# carry no detail attempt; trade_detail_needs_price_backfill? paces them.+ # Transfers waiting only for their note come after everything else.def detail_backfill_sort_key(event)- return [ 0, "" ] unless event.is_a?(Hash)+ return [ 0, 0, "" ] unless event.is_a?(Hash)- [ detail_time(event, DETAIL_BACKFILL_ATTEMPTED_AT_KEY).to_i, (event["timestamp"] || event[:timestamp]).to_s ]+ note_only = cash_note_pending?(event) ? 1 : 0+ [ note_only, detail_time(event, DETAIL_BACKFILL_ATTEMPTED_AT_KEY).to_i, (event["timestamp"] || event[:timestamp]).to_s ]end# Stored trades whose ISIN found no usable exchange symbol are retried at@@ -1310,7 +1355,7 @@ class Provider::TradeRepublicClientnilend- def collect_all_timeline(websocket, known_newest_event_id:, max_pages:, enrich_events: [], timeline_cursors: {}, interrupted_backfills: {})+ def collect_all_timeline(websocket, known_newest_event_id:, max_pages:, enrich_events: [], note_read_event_ids: [], timeline_cursors: {}, interrupted_backfills: {})timeline_cursors = (timeline_cursors || {}).to_h.stringify_keystopics = TIMELINE_TOPICS.index_with do |topic|state = timeline_cursors[topic].is_a?(Hash) ? timeline_cursors[topic].stringify_keys : {}@@ -1329,7 +1374,8 @@ class Provider::TradeRepublicClientevents, detail_warnings, detail_backfill_count = enrich_timeline_details(websocket,skeleton_events,- enrich_events: enrich_events+ enrich_events: enrich_events,+ note_read_event_ids: note_read_event_ids)# Backfilled stored events are older than this sync's pages and must not# pull the list cursor backwards.@@ -1533,12 +1579,16 @@ class Provider::TradeRepublicClient# still consume budget so a bad event cannot starve the rest of the queue# forever within one sync. Stored dividends without their detail are# backfilled too.- def enrich_timeline_details(websocket, events, enrich_events: [])+ def enrich_timeline_details(websocket, events, enrich_events: [], note_read_event_ids: [])warnings = []events = Array(events)+ # The page holding the known newest event is read again as skeletons+ # without markers; a transfer whose note was already read is not.+ note_read_ids = Array(note_read_event_ids).to_set(&:to_s)new_candidates = events.select do |event|event["id"].present? &&- (self.class.incomplete_trade_detail_event?(event) || self.class.dividend_detail_missing?(event))+ (self.class.incomplete_trade_detail_event?(event) || self.class.dividend_detail_missing?(event) ||+ (self.class.cash_note_pending?(event) && !note_read_ids.include?(event["id"].to_s)))endnew_ids = new_candidates.to_set { |event| event["id"].to_s }page_ids = events.filter_map { |event| event["id"].presence&.to_s }.to_set@@ -1549,11 +1599,13 @@ class Provider::TradeRepublicClientnext false if item["id"].blank?next false if new_ids.include?(item["id"].to_s)- # A dividend on this sync's pages is handled there: a new one is- # fetched above, and one that already has its details needs nothing.+ # A dividend or transfer on this sync's pages is handled there: a new+ # one is fetched above, and one that already has its details needs+ # nothing.self.class.incomplete_trade_detail_event?(item) ||self.class.trade_detail_needs_price_backfill?(item) ||- (self.class.dividend_detail_missing?(item) && !page_ids.include?(item["id"].to_s))+ ((self.class.dividend_detail_missing?(item) || self.class.cash_note_pending?(item)) &&+ !page_ids.include?(item["id"].to_s))endbudget = MAX_TIMELINE_DETAILS@@ -1593,6 +1645,11 @@ class Provider::TradeRepublicClientitem: item)detail = detail&.slice(*DIVIDEND_DETAIL_KEYS) if category.to_s == DIVIDEND_DETAIL_CATEGORY+ # A transfer's imported amount stays the timeline amount; only the+ # note comes from the detail.+ if self.class.cash_note_pending?(item)+ detail = (detail || {}).slice("note").merge(NOTE_CHECKED_AT_KEY => Time.current.iso8601)+ endfetched = build_normalized_event(item, category: category, detail: detail)rescue TransientProviderError, Timeout, RateLimitedraise@@ -1605,7 +1662,8 @@ class Provider::TradeRepublicClientdetail_backfill_count += 1 if detail_backfill_improved?(item, result)if self.class.trade_detail_price_unconfirmed?(result)fetched = with_price_backfill_attempt(result)- elsif self.class.incomplete_trade_detail_event?(result) || self.class.dividend_detail_missing?(result)+ elsif self.class.incomplete_trade_detail_event?(result) || self.class.dividend_detail_missing?(result) ||+ self.class.cash_note_pending?(result)fetched = with_detail_backfill_attempt(result)endend@@ -1624,6 +1682,7 @@ class Provider::TradeRepublicClientenddef detail_backfill_improved?(before, after)+ return !self.class.cash_note_pending?(after) if self.class.cash_note_pending?(before)return self.class.trade_detail_complete?(after) if self.class.incomplete_trade_detail_event?(before)self.class.trade_detail_price_unconfirmed?(before) && !self.class.trade_detail_price_unconfirmed?(after)@@ -1740,9 +1799,11 @@ class Provider::TradeRepublicClientgross = quantity.negative? ? amount.abs + deductions : amount.abs - deductionsprice = gross / quantity.abs if gross.positive?end- return nil if quantity.nil? && amount.nil?+ note = find_note(raw)+ return nil if quantity.nil? && amount.nil? && note.nil?{+ "note" => note,"isin" => find_isin(item) || find_isin(raw) || find_logo_isin(raw),"name" => detail_name(item, raw),"quantity" => decimal_string(quantity),@@ -1757,6 +1818,19 @@ class Provider::TradeRepublicClient}.compactend+ # The payment reference: the text of the untitled section of type "note".+ # Found by its type, so it does not depend on the app's language.+ def find_note(raw)+ note = nil+ walk(raw) do |node|+ next if note || !node.is_a?(Hash) || node["type"] != NOTE_SECTION_TYPE || !node["data"].is_a?(Hash)++ text = node["data"]["text"]+ note = text.strip.presence if text.is_a?(String)+ end+ note+ end+def collect_sections(node, result = [], untitled_tables: false)case nodewhen Hashdiff --git a/app/models/trade_republic_account/activities_processor.rb b/app/models/trade_republic_account/activities_processor.rbindex 77920b1cbb..ef8bb95c90 100644--- a/app/models/trade_republic_account/activities_processor.rb+++ b/app/models/trade_republic_account/activities_processor.rb@@ -470,7 +470,9 @@ class TradeRepublicAccount::ActivitiesProcessorcurrency: detail[:currency].presence || currency,date: date,name: event[:title].presence || label,- notes: event[:subtitle].presence,+ # The payment reference. The subtitle only names a status ("Sent"),+ # so it stays in `extra` and is not used as the note.+ notes: detail[:note].presence,source: "trade_republic",category_id: category_for(event, label)&.id,kind: kind || (transfer_event?(event) && !@trade_republic_account.cash? ? "funds_movement" : nil),@@ -488,12 +490,23 @@ class TradeRepublicAccount::ActivitiesProcessor}.compact})+ clear_status_note!(entry, event) if detail[:note].blank?reset_legacy_cash_kind!(entry, event, legacy_kind) if legacy_kind && kind.nil?link_settlement_counterpart!(entry) if settles_tradetrueend+ # Earlier syncs stored the status subtitle ("Sent") as the note. Without a+ # payment reference that text is removed again, unless the user edited it.+ def clear_status_note!(entry, event)+ subtitle = event[:subtitle].presence+ return unless subtitle && entry&.notes == subtitle+ return if entry.protected_from_sync?++ entry.enrich_attribute(:notes, nil, source: "trade_republic")+ end+# The portfolio account holds no cash: Trade Republic settles every trade# on the cash account. Each trade still moves the portfolio's cash in# Sure, so book the opposite leg there and link both legs as a transfer.diff --git a/app/models/trade_republic_item/importer.rb b/app/models/trade_republic_item/importer.rbindex 1e23913ebb..b7fb29300e 100644--- a/app/models/trade_republic_item/importer.rb+++ b/app/models/trade_republic_item/importer.rb@@ -21,6 +21,7 @@ class TradeRepublicItem::Importerknown_newest_event_id: known_newest_event_id,timeline_cursors: force_full_timeline_fetch? ? {} : trade_republic_item.timeline_cursors,enrich_events: events_needing_detail_enrichment,+ note_read_event_ids: note_read_event_ids,symbol_lookup_isins: isins_needing_symbol_lookup,known_instrument_symbols: stored_instrument_symbols)@@ -238,21 +239,41 @@ class TradeRepublicItem::Importer# Incomplete trade-detail events, complete trades without a price read from# the detail (missing, or derived from the rounded total) and dividends- # without their detail, in the client's backlog order.+ # without their detail, and transfers never read for their note, in the+ # client's backlog order.def events_needing_detail_enrichment- portfolio = trade_republic_item.trade_republic_accounts.find_by(kind: "portfolio")- return [] unless portfolio-- Array(portfolio.raw_timeline_payload)+ stored_timeline_events.select do |event|Provider::TradeRepublicClient.incomplete_trade_detail_event?(event) ||Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(event) ||- Provider::TradeRepublicClient.dividend_detail_missing?(event)+ Provider::TradeRepublicClient.dividend_detail_missing?(event) ||+ Provider::TradeRepublicClient.cash_note_pending?(event)end.sort_by { |event| Provider::TradeRepublicClient.detail_backfill_sort_key(event) }.first(Provider::TradeRepublicClient::MAX_TIMELINE_DETAILS)end+ # Transfers whose note was already read. A sync that catches up re-reads+ # the page holding the newest known event, so the client needs these to+ # not fetch them again.+ def note_read_event_ids+ stored_timeline_events+ .select { |event| Provider::TradeRepublicClient.cash_note_read?(event) }+ .filter_map { |event| event["id"].presence }+ end++ # The portfolio and the cash account cap their stored timelines+ # separately, so an old transfer can be left in only one of them.+ def stored_timeline_events+ accounts = trade_republic_item.trade_republic_accounts+ return [] unless accounts.find_by(kind: "portfolio")++ TradeRepublicAccount::DataHelpers.unique_timeline_events(+ accounts.find_by(kind: "portfolio").raw_timeline_payload,+ accounts.find_by(kind: "cash")&.raw_timeline_payload+ )+ 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.diff --git a/test/models/trade_republic_account_activities_processor_test.rb b/test/models/trade_republic_account_activities_processor_test.rbindex 147ec6fd5f..abfd2e8d5f 100644--- a/test/models/trade_republic_account_activities_processor_test.rb+++ b/test/models/trade_republic_account_activities_processor_test.rb@@ -322,6 +322,127 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_nil entry.transaction.investment_activity_labelend+ test "a transfer's payment reference becomes the transaction note, not the status subtitle" do+ import_event({+ id: "evt_transfer_note",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "INCOMING_TRANSFER",+ category: "PAYMENT_RECEIVED",+ title: "Max Mustermann",+ subtitle: "Completed",+ detail: { amount: "50.00", currency: "EUR", note: "Invoice 2026-0001" }+ })++ entry = Entry.find_by(external_id: "trade_republic_event_evt_transfer_note")+ assert_equal "Invoice 2026-0001", entry.notes+ assert_equal "Completed", entry.transaction.extra.dig("trade_republic", "subtitle")+ assert_equal "Invoice 2026-0001", entry.transaction.extra.dig("trade_republic", "provider_detail", "note")+ end++ test "a transfer without a payment reference gets no note" do+ import_event({+ id: "evt_transfer_no_note",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "OUTGOING_TRANSFER",+ category: "POC_CREATED",+ title: "Erika Musterfrau",+ subtitle: "Sent",+ detail: { amount: "20.00", currency: "EUR", note_checked_at: "2026-08-02T10:00:00Z" }+ })++ entry = Entry.find_by(external_id: "trade_republic_event_evt_transfer_no_note")+ assert_nil entry.notes+ assert_nil entry.transaction.extra.dig("trade_republic", "provider_detail", "note_checked_at")+ end++ test "a payment reference replaces the provider's earlier note but not one the user edited" do+ event = {+ id: "evt_transfer_edit",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "INCOMING_TRANSFER",+ category: "PAYMENT_RECEIVED",+ title: "Max Mustermann",+ subtitle: "Completed",+ detail: { amount: "50.00", currency: "EUR" }+ }+ import_event(event)+ entry = Entry.find_by(external_id: "trade_republic_event_evt_transfer_edit")+ entry.update!(notes: "Completed")++ import_event(event.merge(detail: event[:detail].merge(note: "Invoice 2026-0001")))+ assert_equal "Invoice 2026-0001", entry.reload.notes++ entry.update!(notes: "my own note")+ entry.mark_user_modified!+ import_event(event.merge(detail: event[:detail].merge(note: "Invoice 2026-0002")))+ assert_equal "my own note", entry.reload.notes+ end++ test "a status note from an earlier sync is cleared when no payment reference exists" do+ event = {+ id: "evt_status_note",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "OUTGOING_TRANSFER",+ category: "POC_CREATED",+ title: "Erika Musterfrau",+ subtitle: "Sent",+ detail: { amount: "20.00", currency: "EUR" }+ }+ import_event(event)+ entry = Entry.find_by(external_id: "trade_republic_event_evt_status_note")+ entry.update!(notes: "Sent")++ import_event(event)+ assert_nil entry.reload.notes++ entry.update!(notes: "my own note")+ import_event(event)+ assert_equal "my own note", entry.reload.notes+ end++ test "a status note the user edited is kept when no payment reference exists" do+ event = {+ id: "evt_status_note_locked",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "OUTGOING_TRANSFER",+ category: "POC_CREATED",+ title: "Erika Musterfrau",+ subtitle: "Sent",+ detail: { amount: "20.00", currency: "EUR" }+ }+ import_event(event)+ entry = Entry.find_by(external_id: "trade_republic_event_evt_status_note_locked")+ entry.update!(notes: "Sent")+ entry.mark_user_modified!++ import_event(event)++ assert_equal "Sent", entry.reload.notes+ end++ test "a subtitle note on a non-transfer cash event is cleared, a user note on it is kept" do+ event = {+ id: "evt_card_status_note",+ timestamp: "2026-08-01T10:00:00Z",+ eventType: "CARD_TRANSACTION",+ category: "PAYMENT_RECEIVED",+ title: "Marktkauf",+ subtitle: "Card purchase",+ detail: { amount: "12.30", signed_amount: "-12.30", currency: "EUR" }+ }+ import_event(event)+ entry = Entry.find_by(external_id: "trade_republic_event_evt_card_status_note")+ entry.update!(notes: "Card purchase")++ import_event(event)+ assert_nil entry.reload.notes+ assert_equal "Card purchase", entry.transaction.extra.dig("trade_republic", "subtitle")++ entry.update!(notes: "bought for the party")+ import_event(event)+ assert_equal "bought for the party", entry.reload.notes+ end+test "card cash back events that are purchases are imported as expenses with merchant details" doimport_event({id: "evt_card_cash_back",diff --git a/test/models/trade_republic_client_test.rb b/test/models/trade_republic_client_test.rbindex 5cb76f8c56..d6fa222c6c 100644--- a/test/models/trade_republic_client_test.rb+++ b/test/models/trade_republic_client_test.rb@@ -1741,7 +1741,7 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseassert_nil timeline.newest_event_idend- test "card and cash events do not consume timeline detail requests" do+ test "card events do not consume timeline detail requests but transfers read their note" dorequested = []@client.define_singleton_method(:subscribe) do |_websocket, **payload|requested << payload@@ -1763,9 +1763,125 @@ class TradeRepublicClientTest < ActiveSupport::TestCase}], nil, [])- assert_empty requested+ assert_equal [ { type: "timelineDetailV2", id: "transfer-1" } ], requestedassert_equal [ "card-1", "transfer-1" ], events.map { |event| event["id"] }assert_equal(-12.5, events.first.dig("detail", "signed_amount"))+ assert_nil events.first.dig("detail", Provider::TradeRepublicClient::NOTE_CHECKED_AT_KEY)+ end++ test "a transfer detail with a note section stores the note and keeps the timeline amount" do+ freeze_time+ helper = self+ @client.define_singleton_method(:subscribe) { |_websocket, **_payload| helper.send(:transfer_detail, note: "Invoice 2026-0001") }++ events, = @client.send(:resolve_details, Object.new, [ transfer_item ], nil, [])++ detail = events.first["detail"]+ assert_equal "Invoice 2026-0001", detail["note"]+ assert_equal Time.current.iso8601, detail[Provider::TradeRepublicClient::NOTE_CHECKED_AT_KEY]+ assert_equal 50.0, detail["amount"]+ assert_equal 50.0, detail["signed_amount"]+ assert_nil detail["isin"]+ assert_nil detail["quantity"]+ end++ test "a transfer detail without a note section is marked as read" do+ freeze_time+ helper = self+ @client.define_singleton_method(:subscribe) { |_websocket, **_payload| helper.send(:transfer_detail, note: nil) }++ events, = @client.send(:resolve_details, Object.new, [ transfer_item ], nil, [])++ detail = events.first["detail"]+ assert_not detail.key?("note")+ assert_equal Time.current.iso8601, detail[Provider::TradeRepublicClient::NOTE_CHECKED_AT_KEY]+ end++ test "the note is read from the note section only" do+ raw = transfer_detail(note: nil)+ raw["sections"] << { "title" => "Reference", "data" => [ { "title" => "Reference", "detail" => { "text" => "from a table" } } ] }+ raw["sections"] << { "type" => "steps", "title" => "Status", "data" => { "text" => "from steps" } }+ raw["sections"] << { "type" => "header", "data" => { "text" => "from header" } }+ raw["sections"] << { "type" => "note", "data" => [ { "text" => "from a table-shaped note" } ] }++ assert_nil @client.send(:normalize_event_detail, raw, item: transfer_item)++ raw["sections"].insert(2, { "type" => "note", "data" => { "text" => " Invoice 2026-0001 " } })++ assert_equal "Invoice 2026-0001", @client.send(:normalize_event_detail, raw, item: transfer_item)["note"]+ end++ test "a blank note is ignored" do+ assert_nil @client.send(:normalize_event_detail, transfer_detail(note: " "), item: transfer_item)+ end++ test "stored transfers without a read note are fetched from the backlog" do+ requested = []+ helper = self+ @client.define_singleton_method(:subscribe) do |_websocket, **payload|+ requested << payload[:id]+ helper.send(:transfer_detail, note: "Invoice 2026-0001")+ end+ unread = transfer_item(id: "transfer-old").merge("detail" => { "amount" => 50.0, "currency" => "EUR" })+ read = transfer_item(id: "transfer-read").merge(+ "detail" => { "amount" => 50.0, Provider::TradeRepublicClient::NOTE_CHECKED_AT_KEY => "2026-08-02T10:00:00Z" }+ )++ enriched, _warnings, improved = @client.send(:enrich_timeline_details, Object.new, [], enrich_events: [ unread, read ])++ assert_equal [ "transfer-old" ], requested+ assert_equal 1, improved+ assert_equal "Invoice 2026-0001", enriched.find { |event| event["id"] == "transfer-old" }.dig("detail", "note")+ end++ test "transfers repeated on a catch-up page are not fetched again once their note was read" do+ requested = []+ helper = self+ @client.define_singleton_method(:subscribe) do |_websocket, **payload|+ requested << payload[:id]+ helper.send(:transfer_detail, note: nil)+ end+ page = [ transfer_item(id: "transfer-read"), transfer_item(id: "transfer-new") ]+ events = page.map { |item| @client.send(:build_skeleton_event, item, warnings: []) }++ enriched, = @client.send(:enrich_timeline_details, Object.new, events, note_read_event_ids: [ "transfer-read" ])++ assert_equal [ "transfer-new" ], requested+ assert_equal %w[transfer-read transfer-new], enriched.map { |event| event["id"] }+ end++ test "a failed note fetch is marked as attempted and stays pending" do+ freeze_time+ @client.define_singleton_method(:subscribe) { |_websocket, **_payload| raise Provider::TradeRepublicClient::MalformedResponse, "bad detail" }+ stored = transfer_item.merge("detail" => { "amount" => 50.0 })++ enriched, warnings, improved = @client.send(:enrich_timeline_details, Object.new, [], enrich_events: [ stored ])++ event = enriched.find { |candidate| candidate["id"] == "transfer-1" }+ assert_equal 0, improved+ assert_equal [ "detail fetch failed for event transfer-1" ], warnings+ assert_equal Time.current.iso8601, event.dig("detail", Provider::TradeRepublicClient::DETAIL_BACKFILL_ATTEMPTED_AT_KEY)+ assert Provider::TradeRepublicClient.cash_note_pending?(event)+ end++ test "transfers waiting for their note come last in the backlog order" do+ note_only = transfer_item(id: "transfer-old").merge("timestamp" => "2020-01-01T10:00:00Z")+ dividend = {+ "id" => "dividend-1", "timestamp" => "2026-08-01T10:00:00Z", "eventType" => "SSP_CORPORATE_ACTION_CASH",+ "category" => "DIVIDEND", "status" => "EXECUTED", "detail" => { "amount" => 4.3 }+ }++ ordered = [ note_only, dividend ].sort_by { |event| Provider::TradeRepublicClient.detail_backfill_sort_key(event) }++ assert_equal %w[dividend-1 transfer-old], ordered.map { |event| event["id"] }+ end++ test "only transfers and direct debits are checked for a note" do+ assert Provider::TradeRepublicClient.cash_note_pending?(transfer_item(event_type: "BANK_TRANSACTION_OUTGOING_DIRECT_DEBIT"))+ assert_not Provider::TradeRepublicClient.cash_note_pending?(transfer_item(event_type: "CARD_TRANSACTION"))+ assert_not Provider::TradeRepublicClient.cash_note_pending?(transfer_item(event_type: "INTEREST_PAYOUT"))+ assert_not Provider::TradeRepublicClient.cash_note_pending?(transfer_item.merge("status" => "CANCELED"))+ assert_not Provider::TradeRepublicClient.cash_note_pending?(transfer_item.merge("detail" => { "note" => "Invoice 2026-0001" }))endtest "new dividends fetch details without changing the timeline amount" do@@ -2824,6 +2940,33 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseprivate+ def transfer_item(id: "transfer-1", event_type: "PAYMENT_INBOUND")+ {+ "id" => id,+ "timestamp" => "2026-08-01T11:00:00Z",+ "title" => "Max Mustermann",+ "subtitle" => "Completed",+ "eventType" => event_type,+ "amount" => { "value" => 50.0, "currency" => "EUR" }+ }+ end++ # A transfer's detail: header, "Overview" table, the optional untitled+ # note section, then the status steps.+ def transfer_detail(note:)+ sections = [+ { "title" => "You received €50.00", "type" => "header", "data" => { "status" => "executed" } },+ { "title" => "Overview", "type" => "table", "data" => [+ { "title" => "Sender", "detail" => { "text" => "Max Mustermann", "type" => "text" } },+ { "title" => "IBAN", "detail" => { "text" => "DE00 0000 0000 0000 0000 00", "type" => "text" } }+ ] },+ { "title" => "Status", "type" => "steps", "data" => [ { "title" => "Received", "detail" => { "text" => "01 Aug" } } ] },+ { "title" => "Documents", "type" => "documents", "data" => [] }+ ]+ sections.insert(2, { "type" => "note", "data" => { "text" => note } }) unless note.nil?+ { "id" => "transfer-1", "sections" => sections }+ end+# Same shape as bond_purchase_detail, in English, as Sure receives it.def bond_purchase_detail_enrow = ->(title, text) { { "title" => title, "detail" => { "text" => text, "type" => "text" }, "style" => "plain" } }diff --git a/test/models/trade_republic_item_importer_test.rb b/test/models/trade_republic_item_importer_test.rbindex 8aa2f5da73..26f76b7c85 100644--- a/test/models/trade_republic_item_importer_test.rb+++ b/test/models/trade_republic_item_importer_test.rb@@ -790,6 +790,93 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCaseTradeRepublicItem::Importer.new(@item, provider: provider).importend+ test "a stored transfer without a read note is backfilled into the portfolio and cash payloads" do+ stored = {+ "id" => "transfer-old",+ "timestamp" => "2026-06-17T10:00:00Z",+ "title" => "Max Mustermann",+ "subtitle" => "Completed",+ "eventType" => "INCOMING_TRANSFER",+ "category" => "PAYMENT_RECEIVED",+ "detail" => { "amount" => 50.0, "signed_amount" => 50.0, "currency" => "EUR" }+ }+ read = stored.merge("id" => "transfer-read", "detail" => stored["detail"].merge("note_checked_at" => "2026-06-18T10:00:00Z"))+ @item.trade_republic_accounts.create!(+ kind: "portfolio", name: "Portfolio", trade_republic_account_id: "DE-NOTE", currency: "EUR",+ raw_timeline_payload: [ stored, read ]+ )+ @item.trade_republic_accounts.create!(+ kind: "cash", name: "Cash", trade_republic_account_id: "cash:DE-NOTE", currency: "EUR",+ raw_timeline_payload: [ stored, read ]+ )+ with_note = stored.merge(+ "detail" => stored["detail"].merge("note" => "Invoice 2026-0001", "note_checked_at" => "2026-11-10T10:00:00Z")+ )++ provider = mock("trade_republic_provider")+ provider.expects(:sync).with { |args|+ Array(args[:enrich_events]).map { |event| event["id"] } == [ "transfer-old" ]+ }.returns(client_result(+ "status" => "ok",+ "session_txt" => "# refreshed cookies",+ "account" => { "brokerage_account_id" => "DE-NOTE", "currency" => "EUR" },+ "cash" => { "amount" => "1", "currency" => "EUR" },+ "positions" => [],+ "events" => [ with_note ],+ "newest_event_id" => "transfer-read",+ "timeline_pagination_complete" => true,+ "detail_backfill_count" => 1,+ "warnings" => []+ ))++ result = TradeRepublicItem::Importer.new(@item, provider: provider).import++ assert_equal 1, result[:detail_backfill_count]+ %w[portfolio cash].each do |kind|+ events = @item.trade_republic_accounts.find_by!(kind: kind).raw_timeline_payload+ assert_equal "Invoice 2026-0001", events.find { |event| event["id"] == "transfer-old" }.dig("detail", "note"), kind+ assert_nil events.find { |event| event["id"] == "transfer-read" }.dig("detail", "note"), kind+ end+ end++ test "a transfer kept only in the cash payload is backfilled and a read one is passed on" do+ transfer = {+ "id" => "transfer-cash-only",+ "timestamp" => "2026-06-17T10:00:00Z",+ "eventType" => "OUTGOING_TRANSFER",+ "category" => "POC_CREATED",+ "detail" => { "amount" => 20.0, "currency" => "EUR" }+ }+ read = transfer.merge("id" => "transfer-read", "detail" => { "amount" => 5.0, "note_checked_at" => "2026-06-18T10:00:00Z" })+ @item.trade_republic_accounts.create!(+ kind: "portfolio", name: "Portfolio", trade_republic_account_id: "DE-CASHONLY", currency: "EUR",+ raw_timeline_payload: [ read ]+ )+ @item.trade_republic_accounts.create!(+ kind: "cash", name: "Cash", trade_republic_account_id: "cash:DE-CASHONLY", currency: "EUR",+ raw_timeline_payload: [ transfer, read ]+ )++ provider = mock("trade_republic_provider")+ provider.expects(:sync).with { |args|+ Array(args[:enrich_events]).map { |event| event["id"] } == [ "transfer-cash-only" ] &&+ args[:note_read_event_ids] == [ "transfer-read" ]+ }.returns(client_result(+ "status" => "ok",+ "session_txt" => "# refreshed cookies",+ "account" => { "brokerage_account_id" => "DE-CASHONLY", "currency" => "EUR" },+ "cash" => { "amount" => "1", "currency" => "EUR" },+ "positions" => [],+ "events" => [],+ "newest_event_id" => "transfer-read",+ "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" doincomplete = {"id" => "savings-old",