The personal finance app for everyone (by everyone)
Ruby
fix(trade-republic): match the statement for bonus units and stamp duty (#4116)
Simonede20e25a6686
diff --git a/app/models/provider/trade_republic_timeline_event.rb b/app/models/provider/trade_republic_timeline_event.rbindex 73cfdfa241..ced473a43e 100644--- a/app/models/provider/trade_republic_timeline_event.rb+++ b/app/models/provider/trade_republic_timeline_event.rb@@ -191,9 +191,9 @@ module Provider::TradeRepublicTimelineEventnilend- # Trade Republic reports a stamp duty refund as a STAMP_DUTY_TAX_PAID- # event whose subtitle says it is a cancellation. It is a real credit,- # not a cancelled event.+ # Trade Republic turns a cancelled stamp duty charge into a+ # STAMP_DUTY_TAX_PAID event whose subtitle says it is a cancellation. It is+ # not a declined event: the activities processor books nothing for it.def stamp_duty_cancellation?(event)return false unless event.is_a?(Hash)@@ -236,7 +236,7 @@ module Provider::TradeRepublicTimelineEvent# Only subtitle/badge — never title. Titles are often security or# merchant names and can contain substrings like "cancel" without# meaning the event itself failed. A stamp duty cancellation's- # subtitle names the refund, so only its badge counts.+ # subtitle names the cancellation, so only its badge counts.def declined_subtitle?(event)values = [ event[:badge] ]values << event[:subtitle] unless stamp_duty_cancellation?(event)diff --git a/app/models/trade_republic_account/activities_processor.rb b/app/models/trade_republic_account/activities_processor.rbindex 889bf3d6c6..77920b1cbb 100644--- a/app/models/trade_republic_account/activities_processor.rb+++ b/app/models/trade_republic_account/activities_processor.rb@@ -5,6 +5,11 @@ class TradeRepublicAccount::ActivitiesProcessorSTOCK_PERK_EVENT_TYPE = "ACQUISITION_TRADE_PERK"# Shares Trade Republic pays for: a trade only, without a cash leg.BROKER_FUNDED_TRADE_EVENT_TYPES = [ SAVEBACK_EVENT_TYPE, STOCK_PERK_EVENT_TYPE ].freeze+ PRIVATE_MARKETS_TRADE_EVENT_TYPE = "PRIVATE_MARKET_FUND_TRADE_EXECUTED"+ # The bonus units Trade Republic adds to a Private Markets order ("1 %+ # Bonus"). The statement credits their value and buys them with it in one+ # step; the timeline shows only the buy.+ PRIVATE_MARKETS_BONUS_PATTERN = /\bbonus\b/iROUND_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@@ -62,7 +67,7 @@ class TradeRepublicAccount::ActivitiesProcessorreconcile_split_portfolio_transactions!reconcile_moved_crypto_trades!- reconcile_stale_saveback_cash_transactions!+ reconcile_stale_broker_funded_cash_transactions!reconcile_non_importable_entries!reconcile_settlement_counterparts!capture_incomplete_executions@@ -153,8 +158,9 @@ class TradeRepublicAccount::ActivitiesProcessor# Saveback, stock bonuses and Round Up stay classified as POC_CREATED at# the client boundary so other cash withdrawals are unchanged. Routing- # happens here by eventType: Saveback and stock bonuses are a trade only;- # Round Up is a trade plus cash outflow when both accounts are linked.+ # happens here by eventType: Saveback, stock bonuses and Private Markets+ # bonus units are a trade only; Round Up is a trade plus cash outflow when+ # both accounts are linked.# Crypto trades go to the Crypto account once it is linked, except a# portfolio copy the user edited.def processable_event?(event)@@ -165,7 +171,7 @@ class TradeRepublicAccount::ActivitiesProcessorreturn false if @trade_republic_account.crypto? && protected_portfolio_trade?(event)end- return @trade_republic_account.holds_securities? if broker_funded_trade_event?(event_type)+ return @trade_republic_account.holds_securities? if broker_funded_trade_event?(event)return true if round_up_event?(event_type)category = event[:category].to_s@@ -191,8 +197,13 @@ class TradeRepublicAccount::ActivitiesProcessordetail = event[:detail] || {}event_type = event[:eventType].to_s- return process_broker_funded_trade(event, detail, external_id, date) if broker_funded_trade_event?(event_type)+ return process_broker_funded_trade(event, detail, external_id, date) if broker_funded_trade_event?(event)return process_round_up(event, detail, external_id, date) if round_up_event?(event_type)+ # Trade Republic turns a stamp duty charge's timeline item into its+ # cancellation: the item keeps the charge's amount and lists both stamp+ # duty documents. The statement books the charge and the refund, which+ # cancel out, so the item books nothing.+ return nil if Provider::TradeRepublicTimelineEvent.stamp_duty_cancellation?(event)case event_category(event)when CATEGORY_ORDER_EXECUTION@@ -222,8 +233,9 @@ class TradeRepublicAccount::ActivitiesProcessornilend- # Trade Republic pays for Saveback and stock bonuses: no cash moves- # anywhere, so the trade must not move the portfolio's cash either.+ # Trade Republic pays for Saveback, stock bonuses and Private Markets bonus+ # units, so the cash balance does not change and the trade must not move+ # the portfolio's cash either.def process_broker_funded_trade(event, detail, external_id, date)return nil unless @trade_republic_account.holds_securities?@@ -276,8 +288,11 @@ class TradeRepublicAccount::ActivitiesProcessor[ detail[:isin].to_s, date, parse_decimal(detail[:quantity])&.abs ]end- def broker_funded_trade_event?(event_type)- BROKER_FUNDED_TRADE_EVENT_TYPES.include?(event_type)+ def broker_funded_trade_event?(event)+ event_type = event[:eventType].to_s+ return true if BROKER_FUNDED_TRADE_EVENT_TYPES.include?(event_type)++ event_type == PRIVATE_MARKETS_TRADE_EVENT_TYPE && event[:subtitle].to_s.match?(PRIVATE_MARKETS_BONUS_PATTERN)enddef round_up_event?(event_type)@@ -630,17 +645,12 @@ class TradeRepublicAccount::ActivitiesProcessordef event_category(event)signed_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?- # Trade Republic reports a stamp duty cancellation with the same event- # type and sign as the charge; it is a refund to the account.- return CATEGORY_DEPOSIT if Provider::TradeRepublicTimelineEvent.stamp_duty_cancellation?(event)event[:category].to_s.presence ||Provider::TradeRepublicClient::EVENT_TYPE_CATEGORIES[event[:eventType].to_s].to_senddef cash_label_key(event, default:)- return "tax_refund" if Provider::TradeRepublicTimelineEvent.stamp_duty_cancellation?(event)-case event[:eventType].to_swhen "CARD_TRANSACTION", "card_successful_transaction", "CARD_CASH_BACK", "CARD_AFT""card_payment"@@ -688,25 +698,28 @@ 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!+ # Saveback used to import as a cash withdrawal, and Private Markets bonus+ # units as a settled buy. 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. Their settlement counterparts+ # go with them in reconcile_settlement_counterparts!.+ def reconcile_stale_broker_funded_cash_transactions!return unless @trade_republic_account.cash?return if linked_securities_accounts.empty?- saveback_event_ids = Array(@trade_republic_account.raw_timeline_payload).filter_map do |event|+ event_types = timeline_events.each_with_object({}) do |event, types|next unless event.is_a?(Hash)- next unless event["eventType"].to_s == SAVEBACK_EVENT_TYPE- event["id"].presence+ event = event.with_indifferent_access+ next if event[:id].blank? || !broker_funded_trade_event?(event)++ types["trade_republic_event_#{event[:id]}"] = event[:eventType].to_send- return if saveback_event_ids.empty?+ return if event_types.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)+ .where(external_id: event_types.keys).includes(:entryable)removed_count = 0@@ -714,14 +727,14 @@ class TradeRepublicAccount::ActivitiesProcessorcandidates.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+ next if event_type.present? && event_type != event_types[entry.external_id]if entry.protected_from_sync? || entry.split_parent? || entry.split_child?skipped_count += 1DebugLogEntry.capture(category: "sync",level: "info",- message: "Skipped removing protected Saveback cash transaction #{entry.external_id}",+ message: "Skipped removing protected cash leg #{entry.external_id} of a trade Trade Republic paid for",source: "trade_republic",family: @trade_republic_account.trade_republic_item.family,provider_key: "trade_republic",@@ -735,14 +748,15 @@ class TradeRepublicAccount::ActivitiesProcessornextend- # Keep the legacy cash row until the portfolio trade is present so an- # incomplete Saveback detail cannot open a ledger gap.- unless securities_account_with_trade(entry.external_id)+ # Keep the legacy cash row until the portfolio trade is present and no+ # longer books cash, so an incomplete detail or a failed portfolio pass+ # cannot open a ledger gap.+ unless securities_account_with_trade(entry.external_id, amount: 0)skipped_count += 1DebugLogEntry.capture(category: "sync",level: "info",- message: "Skipped removing Saveback cash transaction #{entry.external_id} until portfolio trade exists",+ message: "Skipped removing cash leg #{entry.external_id} of a trade Trade Republic paid for until the portfolio trade books no cash",source: "trade_republic",family: @trade_republic_account.trade_republic_item.family,provider_key: "trade_republic",@@ -764,7 +778,7 @@ class TradeRepublicAccount::ActivitiesProcessorDebugLogEntry.capture(category: "sync",level: "info",- message: "Reconciled stale Saveback cash transactions (removed=#{removed_count}, skipped=#{skipped_count})",+ message: "Reconciled stale cash legs of trades Trade Republic paid for (removed=#{removed_count}, skipped=#{skipped_count})",source: "trade_republic",family: @trade_republic_account.trade_republic_item.family,provider_key: "trade_republic",@@ -784,10 +798,10 @@ class TradeRepublicAccount::ActivitiesProcessorendend- def securities_account_with_trade(external_id)+ def securities_account_with_trade(external_id, **conditions)linked_securities_accounts.find do |securities_account|securities_account.entries- .where(source: "trade_republic", entryable_type: "Trade", external_id: external_id)+ .where(source: "trade_republic", entryable_type: "Trade", external_id: external_id, **conditions).exists?endend@@ -888,18 +902,25 @@ class TradeRepublicAccount::ActivitiesProcessor# 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.+ # on import but never delete existing entries. Stamp duty items are the+ # exception: they carry no merchant text, so their subtitle only states+ # the item's state. A cancelled or voided stamp duty charge removes what+ # earlier syncs booked for it, the charge or a refund.def reconcile_non_importable_entries!explicit_ids = []heuristic_ids = []timeline_events.each do |event|next unless event.is_a?(Hash)- next unless lifecycle_blocks_import?(event)++ cancellation = Provider::TradeRepublicTimelineEvent.stamp_duty_cancellation?(event)+ next unless cancellation || lifecycle_blocks_import?(event)event_id = event["id"].presence || event[:id].presencenext if event_id.blank?- (explicit_lifecycle_block?(event) ? explicit_ids : heuristic_ids) << "trade_republic_event_#{event_id}"+ stamp_duty = (event["eventType"] || event[:eventType]).to_s == Provider::TradeRepublicTimelineEvent::STAMP_DUTY_EVENT_TYPE+ explicit = stamp_duty || explicit_lifecycle_block?(event)+ (explicit ? explicit_ids : heuristic_ids) << "trade_republic_event_#{event_id}"endreturn if explicit_ids.empty? && heuristic_ids.empty?diff --git a/test/models/trade_republic_account_activities_processor_test.rb b/test/models/trade_republic_account_activities_processor_test.rbindex 74784a6c5d..61fb362885 100644--- a/test/models/trade_republic_account_activities_processor_test.rb+++ b/test/models/trade_republic_account_activities_processor_test.rb@@ -382,59 +382,45 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_equal BigDecimal("-500"), Entry.find_by!(external_id: "trade_republic_event_evt_credit_card_cash_in").amountend- test "stamp duty is imported as a charge and its cancellation as a refund" do+ test "a stamp duty cancellation books nothing" do+ # Trade Republic turns the charge's timeline item into its cancellation.+ # The statement books the charge and the refund, which cancel out.@tr_account.update!(raw_timeline_payload: [- {- id: "evt_stamp_duty",- timestamp: "2026-02-18T14:34:02Z",- eventType: "STAMP_DUTY_TAX_PAID",- title: "Stamp duty (Portfolio)",- status: "EXECUTED",- detail: { amount: -22.24, signed_amount: -22.24, currency: "EUR" }- },- {- id: "evt_stamp_duty_cancel",- timestamp: "2026-02-18T09:37:01Z",- eventType: "STAMP_DUTY_TAX_PAID",- title: "Stamp duty (Portfolio)",- subtitle: "Cancellation of stamp duty",- status: "EXECUTED",- detail: { amount: -20.99, signed_amount: -20.99, currency: "EUR" }- }+ stamp_duty_event(id: "evt_stamp_duty_cancel", timestamp: "2026-02-18T09:37:01Z", amount: -15.40, cancellation: true),+ stamp_duty_event(id: "evt_stamp_duty_new", timestamp: "2026-02-18T14:34:02Z", amount: -16.10)])TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process- assert_equal BigDecimal("22.24"), Entry.find_by!(external_id: "trade_republic_event_evt_stamp_duty").amount- assert_equal BigDecimal("-20.99"), Entry.find_by!(external_id: "trade_republic_event_evt_stamp_duty_cancel").amount+ assert_nil Entry.find_by(external_id: "trade_republic_event_evt_stamp_duty_cancel")+ assert_equal BigDecimal("16.10"), Entry.find_by!(external_id: "trade_republic_event_evt_stamp_duty_new").amountend- test "stamp duty cancellation without a status is still imported as a refund" do- import_event({- id: "evt_stamp_duty_cancel_no_status",- timestamp: "2026-02-18T09:37:01Z",- eventType: "STAMP_DUTY_TAX_PAID",- title: "Stamp duty (Portfolio)",- subtitle: "Cancellation of stamp duty",- detail: { amount: -20.99, signed_amount: -20.99, currency: "EUR" }- })+ test "a stamp duty cancellation does not refund an earlier charge of the same amount" do+ # Recurring stamp duty often repeats its amount, so an earlier charge that+ # matches is not evidence of the one the cancellation replaced.+ @tr_account.update!(raw_timeline_payload: [+ stamp_duty_event(id: "evt_stamp_duty", timestamp: "2025-10-07T06:16:00Z", amount: -15.40),+ stamp_duty_event(id: "evt_stamp_duty_cancel", timestamp: "2026-02-18T09:37:01Z", amount: -15.40, cancellation: true, status: nil)+ ])+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process- assert_equal BigDecimal("-20.99"), Entry.find_by!(external_id: "trade_republic_event_evt_stamp_duty_cancel_no_status").amount+ assert_equal BigDecimal("15.40"), Entry.find_by!(external_id: "trade_republic_event_evt_stamp_duty").amount+ assert_nil Entry.find_by(external_id: "trade_republic_event_evt_stamp_duty_cancel")end- test "a stamp duty refund on a portfolio account is not booked as a contribution" do- import_event({- id: "evt_stamp_duty_refund",- timestamp: "2026-02-18T09:37:01Z",- eventType: "STAMP_DUTY_TAX_PAID",- title: "Stamp duty (Portfolio)",- subtitle: "Cancellation of stamp duty",- status: "EXECUTED",- detail: { amount: -20.99, signed_amount: -20.99, currency: "EUR" }- })+ test "removes a refund an earlier sync booked for a stamp duty cancellation" do+ Account::ProviderImportAdapter.new(@account).import_transaction(+ external_id: "trade_republic_event_evt_stamp_duty_cancel",+ amount: BigDecimal("-15.40"),+ currency: "EUR",+ date: Date.parse("2026-02-18"),+ name: "Stamp duty (Portfolio)",+ source: "trade_republic"+ )- transaction = Entry.find_by!(external_id: "trade_republic_event_evt_stamp_duty_refund").transaction- assert_nil transaction.investment_activity_label- assert_equal "standard", transaction.kind+ import_event(stamp_duty_event(id: "evt_stamp_duty_cancel", timestamp: "2026-02-18T09:37:01Z", amount: -15.40, cancellation: true))++ assert_nil Entry.find_by(external_id: "trade_republic_event_evt_stamp_duty_cancel")endtest "a voided stamp duty charge is not imported as a refund" do@@ -450,6 +436,29 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_nil Entry.find_by(external_id: "trade_republic_event_evt_stamp_duty_voided")end+ test "removes a stamp duty charge whose item Trade Republic later voids" do+ import_event(stamp_duty_event(id: "evt_stamp_duty", timestamp: "2026-01-12T10:58:47Z", amount: -15.40))+ assert_equal BigDecimal("15.40"), Entry.find_by!(external_id: "trade_republic_event_evt_stamp_duty").amount++ voided = stamp_duty_event(id: "evt_stamp_duty", timestamp: "2026-01-12T10:58:47Z", amount: -15.40, status: nil)+ import_event(voided.merge(subtitle: "Cancelled"))++ assert_nil Entry.find_by(external_id: "trade_republic_event_evt_stamp_duty")+ end++ test "keeps a card payment flagged only by its subtitle" do+ import_event({+ id: "evt_card", timestamp: "2026-01-12T10:58:47Z", eventType: "CARD_TRANSACTION",+ title: "Cancelled Cafe", status: "EXECUTED", detail: { amount: -4.50, signed_amount: -4.50, currency: "EUR" }+ })+ import_event({+ id: "evt_card", timestamp: "2026-01-12T10:58:47Z", eventType: "CARD_TRANSACTION",+ title: "Cancelled Cafe", subtitle: "Cancelled", detail: { amount: -4.50, signed_amount: -4.50, currency: "EUR" }+ })++ assert Entry.exists?(external_id: "trade_republic_event_evt_card")+ end+test "category direction wins over the provider signed amount" doimport_event({id: "evt_incoming_signed",@@ -709,6 +718,51 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_not @account.entries.exists?(external_id: "trade_republic_settlement_evt_stock_bonus")end+ test "Private Markets bonus units import as a portfolio trade without a cash leg" do+ cash_account, cash_sure = create_linked_cash_account!+ @tr_account.update!(raw_timeline_payload: [ private_markets_event(id: "evt_pm_buy", subtitle: "Buy Order", quantity: "20.0", amount: "2001.0"), private_markets_event ])++ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ bonus = find_trade("trade_republic_event_evt_pm_bonus")+ assert_equal BigDecimal("0.2"), bonus.entryable.qty+ # The statement credits the bonus and buys the units with it; the+ # value stays in the price for the cost basis.+ assert_equal 0, bonus.amount+ assert_in_delta BigDecimal("20.0"), bonus.entryable.qty * bonus.entryable.price, BigDecimal("0.01")+ assert_not Entry.exists?(account: cash_sure, external_id: "trade_republic_event_evt_pm_bonus")+ assert_not @account.entries.exists?(external_id: "trade_republic_settlement_evt_pm_bonus")++ # The order the bonus belongs to still settles against cash.+ assert_equal BigDecimal("2001.0"), cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_pm_buy").amount+ assert @account.entries.exists?(external_id: "trade_republic_settlement_evt_pm_buy")+ end++ test "removes the cash leg an earlier sync booked for Private Markets bonus units" do+ cash_account, cash_sure = create_linked_cash_account!+ # Earlier syncs settled the bonus like the order it belongs to.+ @tr_account.update!(raw_timeline_payload: [ private_markets_event(subtitle: "Buy Order") ])+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ assert cash_sure.entries.exists?(external_id: "trade_republic_event_evt_pm_bonus")+ assert @account.entries.exists?(external_id: "trade_republic_settlement_evt_pm_bonus")++ @tr_account.update!(raw_timeline_payload: [ private_markets_event ])+ # Until the portfolio pass rebooks the trade without cash (it runs first,+ # but can fail), the cash leg stays so the portfolio's cash nets to zero.+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ assert cash_sure.entries.exists?(external_id: "trade_republic_event_evt_pm_bonus")+ assert @account.entries.exists?(external_id: "trade_republic_settlement_evt_pm_bonus")++ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_equal 0, find_trade("trade_republic_event_evt_pm_bonus").amount+ assert_not cash_sure.entries.exists?(external_id: "trade_republic_event_evt_pm_bonus")+ assert_not @account.entries.exists?(external_id: "trade_republic_settlement_evt_pm_bonus")+ end+test "round up imports as a portfolio trade and a cash outflow when split" docash_account, cash_sure = create_linked_cash_account!@@ -1990,6 +2044,38 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCase# Shaped like a stored stock bonus: no status, no amount on the timeline,# shares and value from the detail.+ def private_markets_event(id: "evt_pm_bonus", subtitle: "1 % Bonus", quantity: "0.2", amount: "20.0")+ {+ id: id,+ timestamp: "2025-09-15T13:36:00.000+0000",+ eventType: "PRIVATE_MARKET_FUND_TRADE_EXECUTED",+ category: "orderExecution",+ title: "Private Equity",+ subtitle: subtitle,+ status: "EXECUTED",+ detail: {+ amount: amount,+ signed_amount: "-#{amount}",+ currency: "EUR",+ quantity: quantity,+ isin: "LU0000000001",+ name: "Private Equity"+ }+ }+ end++ def stamp_duty_event(id:, timestamp:, amount:, cancellation: false, status: "EXECUTED", title: "Stamp duty (Portfolio)")+ {+ id: id,+ timestamp: timestamp,+ eventType: "STAMP_DUTY_TAX_PAID",+ title: title,+ subtitle: ("Cancellation of stamp duty" if cancellation),+ status: status,+ detail: { amount: amount, signed_amount: amount, currency: "EUR" }+ }.compact+ end+def stock_bonus_event{id: "evt_stock_bonus",