The personal finance app for everyone (by everyone)
Ruby
Import Trade Republic crypto into a separate Crypto account (#3807)
Niels Eulink7466ce94466e
diff --git a/app/controllers/holdings_controller.rb b/app/controllers/holdings_controller.rbindex c85e7032ff..3408da702f 100644--- a/app/controllers/holdings_controller.rb+++ b/app/controllers/holdings_controller.rb@@ -156,7 +156,7 @@ class HoldingsController < ApplicationControllerendreturn if provider.blank?- values = Array(provider.raw_positions_payload).group_by { |position| position["category"].presence || "brokerage" }+ values = provider.positions.group_by { |position| position["category"].presence || "brokerage" }TradeRepublicClientCategories::ALL.index_with do |category|positions = values.fetch(category, []){diff --git a/app/controllers/trade_republic_items_controller.rb b/app/controllers/trade_republic_items_controller.rbindex 59197d6647..4c97dddf8e 100644--- a/app/controllers/trade_republic_items_controller.rb+++ b/app/controllers/trade_republic_items_controller.rb@@ -348,7 +348,7 @@ class TradeRepublicItemsController < ApplicationController.active.includes(trade_republic_accounts: { account_provider: :account }).flat_map(&:trade_republic_accounts)- .select { |tr_account| tr_account.account_provider.nil? }+ .select { |tr_account| tr_account.account_provider.nil? && tr_account.linkable_to?(@account) }.sort_by { |tr_account| tr_account.updated_at || tr_account.created_at }.reverse@@ -367,7 +367,7 @@ class TradeRepublicItemsController < ApplicationControllerreturnend- unless account.accountable_type.in?(%w[Investment Depository]) &&+ unless tr_account.linkable_to?(account) &&account.account_providers.none? &&account.plaid_account_id.blank? &&account.simplefin_account_id.blank?@@ -434,12 +434,17 @@ class TradeRepublicItemsController < ApplicationController@trade_republic_item.sync_laterend- @linkable_accounts = Current.family.accounts+ linkable_accounts = Current.family.accounts.visible- .where(accountable_type: %w[Investment Depository])+ .where(accountable_type: %w[Investment Depository Crypto]).left_joins(:account_providers).where(account_providers: { id: nil })+ .includes(:accountable).order(:name)+ .to_a+ @linkable_accounts_by_tr_account = @unlinked_accounts.index_with do |tr_account|+ linkable_accounts.select { |linkable| tr_account.linkable_to?(linkable) }+ end@syncing = @trade_republic_item.syncing?@waiting_for_sync = no_accounts && @syncingdiff --git a/app/jobs/trade_republic_repair_job.rb b/app/jobs/trade_republic_repair_job.rbindex e85dfacd61..79dedd7485 100644--- a/app/jobs/trade_republic_repair_job.rb+++ b/app/jobs/trade_republic_repair_job.rb@@ -3,7 +3,7 @@ class TradeRepublicRepairJob < ApplicationJobdef perform(trade_republic_item)trade_republic_item.trade_republic_accounts.includes(account_provider: :account).each do |provider_account|- next unless provider_account.current_account.present?+ next unless provider_account.usable_account.present?beginTradeRepublicAccount::Processor.new(provider_account).processdiff --git a/app/models/account.rb b/app/models/account.rbindex f17ac5b71e..1ca887acfb 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -405,19 +405,26 @@ class Account < ApplicationRecordcreate_and_sync(attributes, skip_initial_sync: true)end+ TRADE_REPUBLIC_ACCOUNT_TYPES = {+ "portfolio" => [ "Investment", "brokerage", "Trade Republic Portfolio" ],+ "cash" => [ "Depository", "checking", "Trade Republic Cash" ],+ # The exchange subtype is the Crypto subtype that supports trades.+ "crypto" => [ "Crypto", "exchange", "Trade Republic Crypto" ]+ }.freeze+def create_from_trade_republic_account(trade_republic_account)family = trade_republic_account.trade_republic_item.family- is_cash = trade_republic_account.cash?+ accountable_type, subtype, default_name = TRADE_REPUBLIC_ACCOUNT_TYPES.fetch(trade_republic_account.kind)attributes = {family: family,- name: trade_republic_account.name.presence || (is_cash ? "Trade Republic Cash" : "Trade Republic Portfolio"),+ name: trade_republic_account.name.presence || default_name,balance: 0,cash_balance: 0,currency: trade_republic_account.currency.presence || family.currency,- accountable_type: is_cash ? "Depository" : "Investment",+ accountable_type: accountable_type,accountable_attributes: {- subtype: is_cash ? "checking" : "brokerage"+ subtype: subtype}}diff --git a/app/models/account/anchorable.rb b/app/models/account/anchorable.rbindex 5983a9b3bc..5dc3261e4a 100644--- a/app/models/account/anchorable.rb+++ b/app/models/account/anchorable.rb@@ -39,9 +39,11 @@ module Account::Anchorableendend- def set_current_balance(balance)+ # Pass schedule_sync: false when the caller schedules the account sync+ # itself, such as a provider sync that syncs its accounts afterwards.+ def set_current_balance(balance, schedule_sync: true)result = current_balance_manager.set_current_balance(balance)- sync_later if result.success?+ sync_later if schedule_sync && result.success?resultenddiff --git a/app/models/trade_republic_account.rb b/app/models/trade_republic_account.rbindex 299e44d32f..3f36536307 100644--- a/app/models/trade_republic_account.rb+++ b/app/models/trade_republic_account.rb@@ -13,7 +13,10 @@ class TradeRepublicAccount < ApplicationRecord# development schema cache has refreshed after a migration. Declaring the# type explicitly keeps the enum valid in that reload window as well.attribute :kind, :string, default: "portfolio"- enum :kind, { portfolio: "portfolio", cash: "cash" }, default: :portfolio+ enum :kind, { portfolio: "portfolio", cash: "cash", crypto: "crypto" }, default: :portfolio++ # Trade Republic lists crypto under pseudo-ISINs starting with XF000.+ CRYPTO_ISIN_PREFIX = "XF000"has_one :account_provider, as: :provider, dependent: :destroyhas_one :account, through: :account_provider, source: :account@@ -22,10 +25,83 @@ class TradeRepublicAccount < ApplicationRecordvalidates :currency, presence: truevalidates :trade_republic_account_id, uniqueness: { scope: :trade_republic_item_id, allow_nil: true }+ def self.crypto_isin?(isin)+ isin.to_s.strip.upcase.start_with?(CRYPTO_ISIN_PREFIX)+ end++ def self.crypto_position?(position)+ return false unless position.is_a?(Hash)++ position = position.with_indifferent_access+ position[:category].to_s == "crypto_wallet" || crypto_isin?(position[:isin])+ end+def current_accountaccount || linked_accountend+ # The linked Sure account, unless it is being deleted or was disabled.+ def usable_account+ acct = current_account+ acct unless acct.nil? || acct.pending_deletion? || acct.disabled?+ end++ def sibling(kind)+ trade_republic_item.trade_republic_accounts.find_by(kind: kind)+ end++ # Manual accounts this provider account can be linked to. Crypto only+ # links to a Crypto exchange account, the Crypto subtype that supports+ # trades, or to an Investment account; Portfolio and Cash keep linking to+ # Investment and Depository accounts.+ def linkable_to?(account)+ case account.accountable_type+ when "Investment" then true+ when "Depository" then !crypto?+ when "Crypto" then crypto? && account.accountable&.subtype == "exchange"+ else false+ end+ end++ # Portfolio and Crypto accounts hold securities; the Cash account settles+ # their trades.+ def holds_securities?+ portfolio? || crypto?+ end++ # Crypto moves to its own account once the user linked the Crypto account.+ # Until then the portfolio keeps holding it.+ def crypto_split?+ sibling("crypto")&.usable_account.present?+ end++ # Trade Republic returns crypto in the portfolio snapshot. The Crypto+ # account holds those positions; the portfolio keeps them only while no+ # Crypto account is linked.+ def positions+ case kind+ when "crypto"+ Array(sibling("portfolio")&.raw_positions_payload).select { |position| self.class.crypto_position?(position) }+ when "portfolio"+ positions = Array(raw_positions_payload)+ crypto_split? ? positions.reject { |position| self.class.crypto_position?(position) } : positions+ else+ []+ end+ end++ def positions_snapshot_complete?+ crypto? ? sibling("portfolio")&.holdings_snapshot_complete? : holdings_snapshot_complete?+ end++ # current_balance on the portfolio values the whole snapshot, crypto+ # included, so a split portfolio leaves out what the Crypto account holds.+ def account_balance+ return current_balance unless portfolio? && crypto_split?++ (current_balance || 0).to_d - (sibling("crypto").current_balance || 0).to_d+ end+def ensure_account_provider!(account = nil)if account_provider.present?account_provider.update!(account: account) if account && account_provider.account_id != account.iddiff --git a/app/models/trade_republic_account/activities_processor.rb b/app/models/trade_republic_account/activities_processor.rbindex 1ea357958a..8abf1135f0 100644--- a/app/models/trade_republic_account/activities_processor.rb+++ b/app/models/trade_republic_account/activities_processor.rb@@ -5,6 +5,16 @@ class TradeRepublicAccount::ActivitiesProcessorROUND_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+ ACTIVITY_LABELS_BY_KEY = {+ "contribution" => "Contribution",+ "withdrawal" => "Withdrawal",+ "interest" => "Interest",+ "dividend" => "Dividend",+ "card_fee" => "Fee",+ "round_up" => "Buy"+ }.freeze+ CASH_UNLABELED_KEYS = %w[contribution withdrawal].freeze+ SETTLEMENT_COUNTERPART_PREFIX = "trade_republic_settlement_"def initialize(trade_republic_account, exchange_securities: {})@trade_republic_account = trade_republic_account@@ -17,6 +27,11 @@ class TradeRepublicAccount::ActivitiesProcessortrade_count = 0transaction_count = 0+ # Also before the events: a trade that moved to the Crypto account has to+ # lose its portfolio counterpart before its settlement can link to a new+ # one on the Crypto account.+ reconcile_settlement_counterparts!+timeline_events.each do |event|next unless event.is_a?(Hash)@@ -40,8 +55,10 @@ class TradeRepublicAccount::ActivitiesProcessorendreconcile_split_portfolio_transactions!+ reconcile_moved_crypto_trades!reconcile_stale_saveback_cash_transactions!reconcile_non_importable_entries!+ reconcile_settlement_counterparts!{ trades: trade_count, transactions: transaction_count }end@@ -74,34 +91,77 @@ class TradeRepublicAccount::ActivitiesProcessor# copies come first so they win the dedupe: a cash snapshot retained from# a failed timeline update can still hold an order execution whose# portfolio copy has since been deleted.+ # The Crypto account stores no timeline of its own: it takes the crypto+ # events from the portfolio's.def timeline_events@timeline_events ||= begin- events = Array(@trade_republic_account.raw_timeline_payload)+ events = if @trade_republic_account.crypto?+ portfolio_timeline_events.select { |event| event.is_a?(Hash) && crypto_event?(event.with_indifferent_access) }+ else+ Array(@trade_republic_account.raw_timeline_payload)+ endevents = portfolio_order_execution_events + events if @trade_republic_account.cash?events.uniq { |event| event.is_a?(Hash) ? (event["id"] || event[:id]).presence || event : event }endenddef portfolio_order_execution_events- portfolio = @trade_republic_account.trade_republic_item.trade_republic_accounts.find_by(kind: "portfolio")- return [] unless portfolio-- Array(portfolio.raw_timeline_payload).select do |event|+ portfolio_timeline_events.select do |event|event.is_a?(Hash) && event_category(event.with_indifferent_access) == CATEGORY_ORDER_EXECUTIONendend+ def portfolio_timeline_events+ Array(@trade_republic_account.sibling("portfolio")&.raw_timeline_payload)+ end++ # Matches the positions the Crypto account holds: an XF000 pseudo-ISIN,+ # or the ISIN of a position Trade Republic lists under crypto. A trade the+ # Crypto account already holds stays there after the position is closed+ # and leaves the snapshot.+ def crypto_event?(event)+ detail = event[:detail]+ return false unless detail.is_a?(Hash)++ isin = detail.with_indifferent_access[:isin].to_s+ TradeRepublicAccount.crypto_isin?(isin) ||+ crypto_position_isins.include?(isin) ||+ crypto_account_trade_ids.include?("trade_republic_event_#{event[:id]}")+ end++ def crypto_account_trade_ids+ @crypto_account_trade_ids ||= begin+ crypto_account = @trade_republic_account.sibling("crypto")&.usable_account+ ids = crypto_account&.entries&.where(source: "trade_republic", entryable_type: "Trade")&.pluck(:external_id)+ Array(ids).to_set+ end+ end++ def crypto_position_isins+ @crypto_position_isins ||= Array(@trade_republic_account.sibling("portfolio")&.raw_positions_payload)+ .select { |position| TradeRepublicAccount.crypto_position?(position) }+ .filter_map { |position| position.with_indifferent_access[:isin].to_s.presence }+ .to_set+ end+# Saveback and Round Up stay classified as POC_CREATED at the client# boundary so other cash withdrawals are unchanged. Routing happens here- # by eventType: Saveback is portfolio-only; Round Up is portfolio trade- # plus cash outflow when both accounts are linked.+ # by eventType: Saveback is 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)event_type = event[:eventType].to_s- return @trade_republic_account.portfolio? if saveback_event?(event_type)+ if crypto_event?(event)+ return false if @trade_republic_account.portfolio? && crypto_split?+ return false if @trade_republic_account.crypto? && protected_portfolio_trade?(event)+ end++ return @trade_republic_account.holds_securities? if saveback_event?(event_type)return true if round_up_event?(event_type)category = event[:category].to_s+ return category == CATEGORY_ORDER_EXECUTION if @trade_republic_account.crypto?return category == CATEGORY_ORDER_EXECUTION if linked_cash_account_present? && @trade_republic_account.portfolio?true@@ -133,17 +193,13 @@ class TradeRepublicAccount::ActivitiesProcessorimport_order_execution(event, detail, external_id, date) ? :trade : nilwhen CATEGORY_DEPOSIT- label = cash_label(event, default: nil)- import_cash_movement(- event, detail, external_id, date,- label: label || t("contribution"), activity_label: label || deposit_activity_label, sign: -1- ) ? :transaction : nil+ import_labeled_cash_movement(event, detail, external_id, date, cash_label_key(event, default: "contribution"), sign: -1)when CATEGORY_WITHDRAWAL- import_cash_movement(event, detail, external_id, date, label: cash_label(event, default: t("withdrawal")), sign: 1) ? :transaction : nil+ import_labeled_cash_movement(event, detail, external_id, date, cash_label_key(event, default: "withdrawal"), sign: 1)when CATEGORY_INTEREST- import_cash_movement(event, detail, external_id, date, label: t("interest"), sign: -1) ? :transaction : nil+ import_labeled_cash_movement(event, detail, external_id, date, "interest", sign: -1)when CATEGORY_DIVIDEND- import_cash_movement(event, detail, external_id, date, label: t("dividend"), sign: -1) ? :transaction : nil+ import_labeled_cash_movement(event, detail, external_id, date, "dividend", sign: -1)endrescue => eDebugLogEntry.capture(@@ -159,19 +215,16 @@ class TradeRepublicAccount::ActivitiesProcessorenddef process_saveback(event, detail, external_id, date)- return nil unless @trade_republic_account.portfolio?+ return nil unless @trade_republic_account.holds_securities?import_order_execution(event, detail, external_id, date) ? :trade : nilenddef process_round_up(event, detail, external_id, date)- if @trade_republic_account.portfolio?+ if @trade_republic_account.holds_securities?import_order_execution(event, detail, external_id, date) ? :trade : nilelse- import_cash_movement(- event, detail, external_id, date,- label: t("round_up"), sign: 1, kind: "investment_contribution"- ) ? :transaction : nil+ import_labeled_cash_movement(event, detail, external_id, date, "round_up", sign: 1, kind: "investment_contribution", settles_trade: true)endend@@ -258,7 +311,8 @@ class TradeRepublicAccount::ActivitiesProcessorendreturn false unless amount && !amount.zero?- signed_amount = is_buy ? -amount.abs : amount.abs+ # Sure trade amounts are cash impact: buys spend cash, sells return it.+ signed_amount = is_buy ? amount.abs : -amount.absif price.nil?# Provider totals include costs: buy total = gross + costs, sell total =# gross - costs. Recover share price from the cash amount accordingly.@@ -325,16 +379,28 @@ class TradeRepublicAccount::ActivitiesProcessorexternal_id,date,label: outflow ? "Buy" : "Sell",+ activity_label: outflow ? "Buy" : "Sell",sign: outflow ? 1 : -1,- kind: outflow ? "investment_contribution" : "funds_movement"+ kind: outflow ? "investment_contribution" : "funds_movement",+ settles_trade: true)end- def import_cash_movement(event, detail, external_id, date, label:, sign:, activity_label: label, kind: nil)+ # The label key names the entry (in the sync's locale) when Trade Republic+ # sends no title, and picks the stored activity label.+ def import_labeled_cash_movement(event, detail, external_id, date, label_key, sign:, kind: nil, settles_trade: false)+ import_cash_movement(+ event, detail, external_id, date,+ label: t(label_key), activity_label: activity_label_for(label_key), sign: sign, kind: kind,+ settles_trade: settles_trade+ ) ? :transaction : nil+ end++ def import_cash_movement(event, detail, external_id, date, label:, activity_label:, sign:, kind: nil, settles_trade: false)amount = parse_decimal(detail[:amount])return false unless amount && !amount.zero?- legacy_contribution = legacy_contribution_external_ids.include?(external_id)+ legacy_kind = legacy_cash_kinds[external_id]entry = import_adapter.import_transaction(external_id: external_id,# The normalized category is the source of truth for direction. TR@@ -348,7 +414,7 @@ class TradeRepublicAccount::ActivitiesProcessornotes: event[:subtitle].presence,source: "trade_republic",category_id: category_for(event, label)&.id,- kind: kind || (transfer_event?(event) ? "funds_movement" : nil),+ kind: kind || (transfer_event?(event) && !@trade_republic_account.cash? ? "funds_movement" : nil),investment_activity_label: activity_label,extra: {trade_republic: {@@ -363,46 +429,139 @@ class TradeRepublicAccount::ActivitiesProcessor}.compact})- reset_legacy_contribution!(entry, event) if legacy_contribution+ reset_legacy_cash_kind!(entry, event, legacy_kind) if legacy_kind && kind.nil?+ link_settlement_counterpart!(entry) if settles_tradetrueend- # The import adapter turns a Contribution label into investment_contribution,- # a kind budgets count as an expense. On the cash account a deposit is money- # arriving on a checking balance, so it carries no investment label.- def deposit_activity_label- @trade_republic_account.cash? ? nil : t("contribution")+ # 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.+ # The portfolio's cash then nets to zero per trade, and the settlement+ # shows which account the money went to. Without the portfolio trade the+ # counterpart would itself leave cash on the portfolio, so it waits for+ # the trade.+ def link_settlement_counterpart!(cash_entry)+ cash_transaction = cash_entry&.entryable+ return unless cash_transaction.is_a?(Transaction)++ securities_account = securities_account_with_trade(cash_entry.external_id)+ return unless securities_account+ return log_settlement_currency_mismatch(cash_entry, securities_account) if securities_account.currency != cash_entry.currency++ counterpart = securities_import_adapter(securities_account).import_transaction(+ external_id: settlement_counterpart_external_id(cash_entry.external_id),+ amount: -cash_entry.amount,+ currency: cash_entry.currency,+ date: cash_entry.date,+ name: cash_entry.amount.positive? ? "Transfer from #{account.name}" : "Transfer to #{account.name}",+ source: "trade_republic",+ kind: "funds_movement",+ investment_activity_label: "Transfer",+ allow_heuristic_matching: false,+ extra: { trade_republic: { settlement_for: cash_entry.external_id } }+ )+ counterpart_transaction = counterpart&.entryable+ return unless counterpart_transaction.is_a?(Transaction)++ inflow, outflow = cash_entry.amount.positive? ? [ counterpart_transaction, cash_transaction ] : [ cash_transaction, counterpart_transaction ]+ return if inflow.transfer.present? || outflow.transfer.present?+ # A user who unlinked the pair keeps it unlinked.+ return if RejectedTransfer.exists?(inflow_transaction_id: inflow.id, outflow_transaction_id: outflow.id)++ Transfer.create!(inflow_transaction: inflow, outflow_transaction: outflow, status: "confirmed")+ end++ # Trade Republic settles in the currency of the portfolio and Crypto+ # accounts, so the counterpart books the settlement amount as is. Should+ # the currencies ever differ, an unconverted counterpart would misstate+ # that account's cash.+ def log_settlement_currency_mismatch(cash_entry, securities_account)+ DebugLogEntry.capture(+ category: "sync",+ level: "warn",+ message: "Skipped Trade Republic settlement counterpart: settlement currency differs from the securities account's",+ source: "trade_republic",+ family: @trade_republic_account.trade_republic_item.family,+ provider_key: "trade_republic",+ account: securities_account,+ metadata: {+ settlement_external_id: cash_entry.external_id,+ settlement_currency: cash_entry.currency,+ securities_account_currency: securities_account.currency+ }+ )+ nil+ end++ def securities_import_adapter(securities_account)+ @securities_import_adapters ||= {}+ @securities_import_adapters[securities_account.id] ||= Account::ProviderImportAdapter.new(securities_account)+ end++ def settlement_counterpart_external_id(settlement_external_id)+ settlement_external_id.sub(/\Atrade_republic_event_/, SETTLEMENT_COUNTERPART_PREFIX)end- # Earlier syncs stored cash-account deposits as investment contributions.- # The adapter never clears the category and label it assigned with that- # kind, so reset untouched inflows outside a matched transfer. Callers only- # pass rows stored with that kind: a family can assign the same category or- # label through a Rule, which must survive a sync.- def reset_legacy_contribution!(entry, event)+ # Stored as fixed Transaction::ACTIVITY_LABELS values: budgets, the import+ # adapter and the label picker compare against them, so they must not+ # follow the locale a sync runs in. Card activity carries no label. On the+ # cash account deposits and withdrawals move money on a checking balance,+ # so they carry none either; a Contribution label would make the adapter+ # book them as investment_contribution.+ def activity_label_for(label_key)+ return nil if @trade_republic_account.cash? && CASH_UNLABELED_KEYS.include?(label_key)++ ACTIVITY_LABELS_BY_KEY[label_key]+ end++ # Cash-account deposits and withdrawals are imported as standard+ # transactions; automatic transfer matching turns them into a transfer+ # when the counterpart account is in Sure, whatever the payment type.+ # Earlier syncs stored deposits as investment contributions (with the+ # category and label the adapter assigned with that kind) and payment+ # events as funds movements. Reset those rows unless the user edited them+ # or they belong to a matched transfer. Only rows stored with such a kind+ # are passed in: a family can assign the same category or label through a+ # Rule, which must survive a sync.+ def reset_legacy_cash_kind!(entry, event, legacy_kind)transaction = entry&.entryable- return unless transaction.is_a?(Transaction) && entry.amount.negative?+ return unless transaction.is_a?(Transaction)return if entry.protected_from_sync? || transaction.transfer.present?- attrs = { kind: transfer_event?(event) ? "funds_movement" : "standard" }- attrs[:category_id] = nil if investment_contribution_category_ids.include?(transaction.category_id)- attrs[:investment_activity_label] = nil if transaction.investment_activity_label == "Contribution"- transaction.update!(attrs)+ if legacy_kind == "investment_contribution"+ return unless entry.amount.negative?++ attrs = { kind: "standard" }+ attrs[:category_id] = nil if investment_contribution_category_ids.include?(transaction.category_id) &&+ !rule_assigned?(transaction, :category_id)+ attrs[:investment_activity_label] = nil if transaction.investment_activity_label == "Contribution" &&+ !rule_assigned?(transaction, :investment_activity_label)+ transaction.update!(attrs)+ elsif transfer_event?(event)+ transaction.update!(kind: "standard")+ end+ end++ # A Rule can assign the same category or label to a legacy row before this+ # reset runs; the value then belongs to the Rule.+ def rule_assigned?(transaction, attribute)+ transaction.data_enrichments.exists?(attribute_name: attribute.to_s, source: "rule")end- # Read before the first cash movement is imported: the adapter overwrites- # the kind of transfer events, so the stored kind is gone afterwards.- def legacy_contribution_external_ids- @legacy_contribution_external_ids ||=+ # Read before the first cash movement is imported, while it still holds+ # the kind earlier syncs stored.+ def legacy_cash_kinds+ @legacy_cash_kinds ||=if @trade_republic_account.cash?- Transaction.investment_contribution+ Transaction.where(kind: %w[investment_contribution funds_movement]).joins(:entry).where(entries: { account_id: account.id, source: "trade_republic" })- .pluck("entries.external_id")- .to_set+ .pluck("entries.external_id", :kind)+ .to_helse- Set.new+ {}endend@@ -432,22 +591,20 @@ class TradeRepublicAccount::ActivitiesProcessorProvider::TradeRepublicClient::EVENT_TYPE_CATEGORIES[event[:eventType].to_s].to_send- def cash_label(event, default:)+ def cash_label_key(event, default:)case event[:eventType].to_s- when "CARD_TRANSACTION", "card_successful_transaction"- t("card_payment")+ when "CARD_TRANSACTION", "card_successful_transaction", "CARD_CASH_BACK"+ "card_payment"when "CARD_ATM_WITHDRAWAL"- t("cash_withdrawal")+ "cash_withdrawal"when "CARD_ORDER_FEE"- t("card_fee")- when "CARD_CASH_BACK"- t("card_payment")+ "card_fee"when "card_refund", "CARD_REFUND"- t("card_refund")+ "card_refund"when "TAX_REFUND", "SSP_TAX_CORRECTION", "ssp_tax_correction_invoice"- t("tax_refund")+ "tax_refund"when ROUND_UP_EVENT_TYPE- t("round_up")+ "round_up"elsedefaultend@@ -487,9 +644,7 @@ class TradeRepublicAccount::ActivitiesProcessor# 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+ return if linked_securities_accounts.empty?saveback_event_ids = Array(@trade_republic_account.raw_timeline_payload).filter_map do |event|next unless event.is_a?(Hash)@@ -533,7 +688,7 @@ class TradeRepublicAccount::ActivitiesProcessor# 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)+ unless securities_account_with_trade(entry.external_id)skipped_count += 1DebugLogEntry.capture(category: "sync",@@ -545,8 +700,7 @@ class TradeRepublicAccount::ActivitiesProcessoraccount: account,metadata: {trade_republic_account_id: @trade_republic_account.id,- external_id: entry.external_id,- portfolio_account_id: portfolio_account.id+ external_id: entry.external_id})next@@ -574,21 +728,112 @@ class TradeRepublicAccount::ActivitiesProcessor)end- def linked_portfolio_account- portfolio_tr = @trade_republic_account.trade_republic_item.trade_republic_accounts.find_by(kind: "portfolio")- return unless portfolio_tr+ # The Portfolio and Crypto accounts whose trades the Cash account settles.+ def linked_securities_accounts+ @linked_securities_accounts ||= %w[portfolio crypto].filter_map do |kind|+ @trade_republic_account.sibling(kind)&.usable_account+ end+ end++ def securities_account_with_trade(external_id)+ linked_securities_accounts.find do |securities_account|+ securities_account.entries+ .where(source: "trade_republic", entryable_type: "Trade", external_id: external_id)+ .exists?+ end+ end++ # Runs last, after this run removed stale cash entries and the portfolio+ # run removed stale trades: a counterpart without both would put cash on+ # the portfolio again.+ def reconcile_settlement_counterparts!+ return unless @trade_republic_account.cash?++ settlement_ids = account.entries+ .where(source: "trade_republic", entryable_type: "Transaction")+ .pluck(:external_id)+ linked_securities_accounts.each do |securities_account|+ reconcile_settlement_counterparts_on!(securities_account, settlement_ids)+ end+ end++ def reconcile_settlement_counterparts_on!(securities_account, settlement_ids)+ trade_ids = securities_account.entries+ .where(source: "trade_republic", entryable_type: "Trade")+ .pluck(:external_id)+ linked_ids = (settlement_ids & trade_ids).map { |id| settlement_counterpart_external_id(id) }++ stale_entries = securities_account.entries+ .where(source: "trade_republic", entryable_type: "Transaction")+ .where("external_id LIKE ?", "#{ActiveRecord::Base.sanitize_sql_like(SETTLEMENT_COUNTERPART_PREFIX)}%")+ .where.not(external_id: linked_ids)++ removed_count = 0+ stale_entries.find_each do |entry|+ next if entry.protected_from_sync?++ entry.destroy!+ removed_count += 1+ end+ return unless removed_count.positive?++ DebugLogEntry.capture(+ category: "sync",+ level: "info",+ message: "Removed #{removed_count} Trade Republic settlement counterpart(s) without a settlement or trade",+ source: "trade_republic",+ family: @trade_republic_account.trade_republic_item.family,+ provider_key: "trade_republic",+ account: securities_account,+ metadata: { trade_republic_account_id: @trade_republic_account.id, removed_count: removed_count }+ )+ end++ # Once the Crypto account is linked, it imports the crypto trades the+ # portfolio held until then. Remove the portfolio copies after the Crypto+ # account has its own. A trade whose portfolio copy or settlement+ # counterpart the user edited stays on the portfolio, and the Crypto+ # account skips it (see processable_event?).+ def reconcile_moved_crypto_trades!+ return unless @trade_republic_account.crypto?- portfolio_account = portfolio_tr.current_account+ portfolio_account = @trade_republic_account.sibling("portfolio")&.usable_accountreturn unless portfolio_account- return if portfolio_account.pending_deletion? || portfolio_account.disabled?- portfolio_account+ moved_ids = account.entries.where(source: "trade_republic", entryable_type: "Trade").pluck(:external_id)+ return if moved_ids.empty?++ removed_count = 0+ portfolio_account.entries+ .where(source: "trade_republic", entryable_type: "Trade", external_id: moved_ids)+ .find_each do |entry|+ next if entry.protected_from_sync?++ entry.destroy!+ removed_count += 1+ end+ return unless removed_count.positive?++ DebugLogEntry.capture(+ category: "sync",+ level: "info",+ message: "Moved #{removed_count} Trade Republic crypto trade(s) from the portfolio to the Crypto account",+ source: "trade_republic",+ family: @trade_republic_account.trade_republic_item.family,+ provider_key: "trade_republic",+ account: portfolio_account,+ metadata: { trade_republic_account_id: @trade_republic_account.id, removed_count: removed_count }+ )end- def portfolio_saveback_trade_present?(portfolio_account, external_id)+ def protected_portfolio_trade?(event)+ portfolio_account = @trade_republic_account.sibling("portfolio")&.current_account+ return false unless portfolio_account++ external_id = "trade_republic_event_#{event[:id]}"portfolio_account.entries- .where(source: "trade_republic", entryable_type: "Trade", external_id: external_id)- .exists?+ .where(source: "trade_republic", external_id: [ external_id, settlement_counterpart_external_id(external_id) ])+ .any?(&:protected_from_sync?)end# Remove previously imported entries whose upstream events are now deleted,@@ -675,6 +920,12 @@ class TradeRepublicAccount::ActivitiesProcessor)end+ def crypto_split?+ return @crypto_split if defined?(@crypto_split)++ @crypto_split = @trade_republic_account.crypto_split?+ end+def linked_cash_account_present?@trade_republic_account.trade_republic_item.trade_republic_accounts.where(kind: "cash")diff --git a/app/models/trade_republic_account/holdings_processor.rb b/app/models/trade_republic_account/holdings_processor.rbindex 68a0d61b19..cf8d9a3d5d 100644--- a/app/models/trade_republic_account/holdings_processor.rb+++ b/app/models/trade_republic_account/holdings_processor.rb@@ -9,7 +9,7 @@ class TradeRepublicAccount::HoldingsProcessordef processreturn unless account.present?- positions = Array(@trade_republic_account.raw_positions_payload)+ positions = @trade_republic_account.positionsprocessed_count = positions.count do |position|process_position(position.with_indifferent_access)end@@ -17,7 +17,7 @@ class TradeRepublicAccount::HoldingsProcessor# A validated, complete snapshot is authoritative. Reconcile only after# every position was imported successfully; partial provider data must# preserve existing holdings.- if @trade_republic_account.holdings_snapshot_complete? && processed_count == positions.size+ if @trade_republic_account.positions_snapshot_complete? && processed_count == positions.sizereconcile_stale_holdings!(positions)endenddiff --git a/app/models/trade_republic_account/processor.rb b/app/models/trade_republic_account/processor.rbindex fba43d2b90..efb00de26b 100644--- a/app/models/trade_republic_account/processor.rb+++ b/app/models/trade_republic_account/processor.rb@@ -26,7 +26,7 @@ class TradeRepublicAccount::Processorenddef update_account_balance!- total_balance = trade_republic_account.current_balance || 0+ total_balance = trade_republic_account.account_balance || 0cash_balance = trade_republic_account.cash_balance || 0account.assign_attributes(@@ -35,6 +35,9 @@ class TradeRepublicAccount::Processorcurrency: trade_republic_account.currency)account.save!- account.set_current_balance(total_balance)+ # TradeRepublicItem#schedule_account_syncs syncs the account once every+ # Trade Republic account has been processed. A sync started here would+ # run before the other accounts book their settlements, and then again.+ account.set_current_balance(total_balance, schedule_sync: false)endenddiff --git a/app/models/trade_republic_item.rb b/app/models/trade_republic_item.rbindex 5b707b57c3..87a49ae702 100644--- a/app/models/trade_republic_item.rb+++ b/app/models/trade_republic_item.rb@@ -64,11 +64,16 @@ class TradeRepublicItem < ApplicationRecorddef process_accountsreturn [] if trade_republic_accounts.empty?- # Portfolio before cash so Saveback trades exist before cash reconciliation- # removes legacy Saveback withdrawals in the same process_accounts pass.+ # Portfolio and Crypto before cash so Saveback trades exist before cash+ # reconciliation removes legacy Saveback withdrawals in the same+ # process_accounts pass, and cash settlements find the trade they link to.+ # The accounts are processed without a spanning transaction: each pass+ # derives its entries and reconciliations from the stored snapshots, so+ # when one account fails, the next successful sync repairs any trade or+ # settlement counterpart left halfway through a move.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)+ .order(Arel.sql("CASE kind WHEN 'portfolio' THEN 0 WHEN 'crypto' THEN 1 WHEN 'cash' THEN 2 ELSE 3 END"), :id).each_with_object([]) do |tr_account, results|account = tr_account.current_accountnext unless account@@ -191,7 +196,7 @@ class TradeRepublicItem < ApplicationRecordaccount = provider_account.current_accountnext if account.blank?- expected = provider_account.current_balance.to_d+ expected = provider_account.account_balance.to_dactual = account.balance.to_ddifference = (expected - actual).abs{diff --git a/app/models/trade_republic_item/importer.rb b/app/models/trade_republic_item/importer.rbindex 05e3676dba..3be0088994 100644--- a/app/models/trade_republic_item/importer.rb+++ b/app/models/trade_republic_item/importer.rb@@ -99,6 +99,43 @@ class TradeRepublicItem::Importerwarnings: [],domain_statuses: domain_statuses)+ upsert_crypto_account(account_id, currency, domain_statuses)+ end++ # Crypto gets its own account because Sure has a Crypto account type.+ # It reads its positions and trades from the portfolio payloads, so only+ # its balance is stored here. Created once the portfolio holds or traded+ # crypto; it stays unlinked until the user sets it up.+ def upsert_crypto_account(account_id, currency, domain_statuses)+ portfolio = trade_republic_item.trade_republic_accounts.find_by(kind: "portfolio")+ crypto = trade_republic_item.trade_republic_accounts.find_by(kind: "crypto")+ return if crypto.nil? && !holds_or_traded_crypto?(portfolio)++ crypto ||= trade_republic_item.trade_republic_accounts.build(kind: "crypto")++ crypto.assign_attributes(+ trade_republic_account_id: "crypto:#{account_id}",+ name: build_account_name(account_id, kind: "crypto"),+ currency: currency,+ cash_balance: 0+ )+ if domain_statuses["portfolio"] == "success"+ crypto.current_balance = positions_value(crypto_positions(portfolio), fallback: crypto.current_balance)+ end+ crypto.save!+ end++ def holds_or_traded_crypto?(portfolio)+ return false unless portfolio++ crypto_positions(portfolio).any? || Array(portfolio.raw_timeline_payload).any? do |event|+ detail = event.is_a?(Hash) ? (event["detail"] || event[:detail]) : nil+ detail.is_a?(Hash) && TradeRepublicAccount.crypto_isin?(detail["isin"] || detail[:isin])+ end+ end++ def crypto_positions(portfolio)+ Array(portfolio&.raw_positions_payload).select { |position| TradeRepublicAccount.crypto_position?(position) }enddef upsert_kind(kind:, external_id:, name:, currency:, current_balance:, cash_balance:, positions:, events:, instrument_symbols:, warnings:, domain_statuses:, unresolved_symbol_isins: [])@@ -375,7 +412,10 @@ class TradeRepublicItem::Importerenddef portfolio_balance(data, fallback: nil)- positions = Array(data["positions"])+ positions_value(Array(data["positions"]), fallback: fallback)+ end++ def positions_value(positions, fallback: nil)return BigDecimal("0") if positions.empty?values = positions.map do |position|@@ -393,7 +433,7 @@ class TradeRepublicItem::Importerdef build_account_name(account_id, kind:)base = I18n.t("trade_republic_items.defaults.name")- suffix = kind == "cash" ? "Cash" : "Portfolio"+ suffix = { "cash" => "Cash", "crypto" => "Crypto" }.fetch(kind, "Portfolio")account_id.present? ? "#{base} #{suffix} (#{account_id})" : "#{base} #{suffix}"enddiff --git a/app/views/trade_republic_items/setup_accounts.html.erb b/app/views/trade_republic_items/setup_accounts.html.erbindex ec1510e191..06984e6c92 100644--- a/app/views/trade_republic_items/setup_accounts.html.erb+++ b/app/views/trade_republic_items/setup_accounts.html.erb@@ -78,7 +78,7 @@<p class="text-sm text-secondary"><%= t(".available_accounts.account_summary",- account_type: tr_account.cash? ? t(".available_accounts.account_type_cash") : t(".available_accounts.account_type_investment"),+ account_type: { "cash" => t(".available_accounts.account_type_cash"), "crypto" => t(".available_accounts.account_type_crypto") }.fetch(tr_account.kind, t(".available_accounts.account_type_investment")),balance: number_to_currency(tr_account.current_balance || 0, unit: Money::Currency.new(tr_account.currency.presence || Current.family.currency).symbol)) %></p>@@ -109,17 +109,18 @@<% end %><% end %>- <% if @unlinked_accounts.any? && @linkable_accounts.any? %>+ <% if @linkable_accounts_by_tr_account.values.any?(&:present?) %><div class="border-t border-secondary pt-4 mt-2"><p class="text-xs text-secondary mb-3"><%= t(".link_existing.description") %></p><div class="space-y-2">- <% @unlinked_accounts.each do |tr_account| %>+ <% @linkable_accounts_by_tr_account.each do |tr_account, linkable_accounts| %>+ <% next if linkable_accounts.empty? %><%= form_with url: link_existing_account_trade_republic_items_path, method: :post, data: { turbo_frame: "_top" } do |link_form| %><%= link_form.hidden_field :trade_republic_account_id, value: tr_account.id %><p class="text-xs text-primary mb-1"><%= tr_account.name %></p><div class="flex items-center gap-2"><%= link_form.select :account_id,- options_for_select(@linkable_accounts.map { |a| [ t(".link_existing.manual_account_option", name: a.name, balance: number_to_currency(a.balance, unit: Money::Currency.new(a.currency.presence || Current.family.currency).symbol)), a.id ] }),+ options_for_select(linkable_accounts.map { |a| [ t(".link_existing.manual_account_option", name: a.name, balance: number_to_currency(a.balance, unit: Money::Currency.new(a.currency.presence || Current.family.currency).symbol)), a.id ] }),{ prompt: t(".link_existing.select_prompt") },{ class: "bg-container border border-primary rounded px-2 py-1 text-sm text-primary flex-1 min-w-0", required: true } %><%= render DS::Button.new(diff --git a/config/locales/views/trade_republic_items/de.yml b/config/locales/views/trade_republic_items/de.ymlindex db993a9bf8..0de927cb2d 100644--- a/config/locales/views/trade_republic_items/de.yml+++ b/config/locales/views/trade_republic_items/de.yml@@ -74,6 +74,7 @@ de:account_id: "Konto-ID: %{account_id}"account_type_investment: "Investment-Portfolio"account_type_cash: "Cash-Konto"+ account_type_crypto: "Krypto-Konto"link_existing:description: "Alternativ kannst du das gefundene Trade-Republic-Konto mit einem bestehenden manuellen Investmentkonto verknüpfen."manual_account_option: "%{name} (%{balance})"diff --git a/config/locales/views/trade_republic_items/en.yml b/config/locales/views/trade_republic_items/en.ymlindex f7561a72d2..5fcd2e9ea1 100644--- a/config/locales/views/trade_republic_items/en.yml+++ b/config/locales/views/trade_republic_items/en.yml@@ -74,6 +74,7 @@ en:title: Available accountaccount_type_investment: Investment portfolioaccount_type_cash: Cash account+ account_type_crypto: Crypto accountaccount_summary: "%{account_type} • Balance: %{balance}"account_id: "Account ID: %{account_id}"link_existing:diff --git a/db/migrate/20260928090000_normalize_trade_republic_activity_labels.rb b/db/migrate/20260928090000_normalize_trade_republic_activity_labels.rbnew file mode 100644index 0000000000..68749c5b7f--- /dev/null+++ b/db/migrate/20260928090000_normalize_trade_republic_activity_labels.rb@@ -0,0 +1,85 @@+# Trade Republic syncs stored translated activity labels ("Storting",+# "Kaartbetaling", "Card payment") in whichever locale the sync job ran.+# Budgets, the import adapter and the label picker only know the fixed+# Transaction::ACTIVITY_LABELS values, so map each translation back to the+# value the importer now stores. Values outside that list are always from+# the importer: the label picker and Rules can only set listed values.+# English syncs stored listed values ("Withdrawal", "Contribution") that the+# importer no longer sets on non-investment accounts; those are cleared only+# when neither the user nor a Rule or other enrichment set the label.+class NormalizeTradeRepublicActivityLabels < ActiveRecord::Migration[8.1]+ LABEL_SCOPE = "trade_republic_items.activities.labels"++ # Label key => [label on an investment account, label on any other account]+ TARGETS = {+ "contribution" => [ "Contribution", nil ],+ "withdrawal" => [ "Withdrawal", nil ],+ "interest" => [ "Interest", "Interest" ],+ "dividend" => [ "Dividend", "Dividend" ],+ "card_fee" => [ "Fee", "Fee" ],+ "round_up" => [ "Buy", "Buy" ],+ "card_payment" => [ nil, nil ],+ "cash_withdrawal" => [ nil, nil ],+ "card_refund" => [ nil, nil ],+ "tax_refund" => [ nil, nil ]+ }.freeze++ def up+ TARGETS.each do |key, (investment_label, other_label)|+ clear_listed_labels(key, other_label)++ stale = translations_for(key) - Transaction::ACTIVITY_LABELS+ next if stale.empty?++ execute ActiveRecord::Base.sanitize_sql_array([ <<~SQL.squish, { investment_label:, other_label:, stale: } ])+ UPDATE transactions+ SET investment_activity_label = CASE+ WHEN accounts.accountable_type = 'Investment' THEN CAST(:investment_label AS varchar)+ ELSE CAST(:other_label AS varchar)+ END+ FROM entries+ JOIN accounts ON accounts.id = entries.account_id+ WHERE entries.entryable_type = 'Transaction'+ AND entries.entryable_id = transactions.id+ AND entries.source = 'trade_republic'+ AND NOT (COALESCE(transactions.locked_attributes, '{}'::jsonb) ? 'investment_activity_label')+ AND transactions.investment_activity_label IN (:stale)+ SQL+ end+ end++ # The translated labels are not worth restoring.+ def down+ end++ private++ def clear_listed_labels(key, other_label)+ listed = translations_for(key) & Transaction::ACTIVITY_LABELS+ return if other_label || listed.empty?++ execute ActiveRecord::Base.sanitize_sql_array([ <<~SQL.squish, { listed: } ])+ UPDATE transactions+ SET investment_activity_label = NULL+ FROM entries+ JOIN accounts ON accounts.id = entries.account_id+ WHERE entries.entryable_type = 'Transaction'+ AND entries.entryable_id = transactions.id+ AND entries.source = 'trade_republic'+ AND entries.user_modified = false+ AND accounts.accountable_type <> 'Investment'+ AND NOT (COALESCE(transactions.locked_attributes, '{}'::jsonb) ? 'investment_activity_label')+ AND transactions.investment_activity_label IN (:listed)+ AND NOT EXISTS (+ SELECT 1 FROM data_enrichments+ WHERE data_enrichments.enrichable_type = 'Transaction'+ AND data_enrichments.enrichable_id = transactions.id+ AND data_enrichments.attribute_name = 'investment_activity_label'+ )+ SQL+ end++ def translations_for(key)+ I18n.available_locales.filter_map { |locale| I18n.t(key, scope: LABEL_SCOPE, locale: locale, default: nil) }.uniq+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 7f96682ac5..d437519851 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[8.1].define(version: 2026_09_27_161700) do+ActiveRecord::Schema[8.1].define(version: 2026_09_28_090000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pg_catalog.plpgsql"enable_extension "pgcrypto"diff --git a/test/controllers/trade_republic_items_controller_test.rb b/test/controllers/trade_republic_items_controller_test.rbindex 69ac8bcf4b..d52634487a 100644--- a/test/controllers/trade_republic_items_controller_test.rb+++ b/test/controllers/trade_republic_items_controller_test.rb@@ -135,6 +135,19 @@ class TradeRepublicItemsControllerTest < ActionDispatch::IntegrationTestassert_not_nil provider_account.current_accountend+ test "complete account setup creates a Crypto exchange account for the Crypto account" do+ item = trade_republic_items(:configured_item)+ provider_account = item.trade_republic_accounts.create!(+ name: "Trade Republic Crypto", kind: "crypto", trade_republic_account_id: "crypto:DE1", currency: "EUR"+ )++ post complete_account_setup_trade_republic_item_url(item), params: { account_ids: [ provider_account.id ] }++ account = provider_account.reload.current_account+ assert_equal "Crypto", account.accountable_type+ assert_equal "exchange", account.accountable.subtype+ end+test "complete account setup rolls back an account when linking fails" doitem = trade_republic_items(:configured_item)provider_account = trade_republic_accounts(:main_account)@@ -173,6 +186,50 @@ class TradeRepublicItemsControllerTest < ActionDispatch::IntegrationTestassert_equal item, trade_republic_account.trade_republic_itemend+ test "link_existing_account links the Crypto account only to a Crypto exchange account" do+ item = trade_republic_items(:configured_item)+ crypto_provider = item.trade_republic_accounts.create!(+ name: "Trade Republic Crypto", kind: "crypto", trade_republic_account_id: "crypto:DE1", currency: "EUR"+ )+ family = item.family+ wallet = family.accounts.create!(name: "Wallet", balance: 0, currency: "EUR", accountable: Crypto.new(subtype: "wallet"))+ exchange = family.accounts.create!(name: "Exchange", balance: 0, currency: "EUR", accountable: Crypto.new(subtype: "exchange"))+ TradeRepublicAccount::Processor.any_instance.stubs(:process)++ post link_existing_account_trade_republic_items_url, params: { account_id: wallet.id, trade_republic_account_id: crypto_provider.id }+ assert_nil crypto_provider.reload.current_account++ post link_existing_account_trade_republic_items_url, params: { account_id: exchange.id, trade_republic_account_id: crypto_provider.id }+ assert_equal exchange, crypto_provider.reload.current_account+ end++ test "account setup offers only matching manual accounts for linking" do+ item = trade_republic_items(:configured_item)+ item.trade_republic_accounts.create!(+ name: "Trade Republic Crypto", kind: "crypto", trade_republic_account_id: "crypto:DE1", currency: "EUR"+ )+ item.family.accounts.create!(name: "Cold Wallet", balance: 0, currency: "EUR", accountable: Crypto.new(subtype: "wallet"))+ item.family.accounts.create!(name: "Crypto Exchange", balance: 0, currency: "EUR", accountable: Crypto.new(subtype: "exchange"))++ get setup_accounts_trade_republic_item_url(item)++ assert_response :success+ options = css_select("select[name='account_id'] option").map(&:text)+ assert options.any? { |option| option.start_with?("Crypto Exchange") }+ assert_not options.any? { |option| option.start_with?("Cold Wallet") }+ end++ test "link_existing_account does not link the portfolio to a Crypto account" do+ item = trade_republic_items(:configured_item)+ portfolio = trade_republic_accounts(:main_account)+ exchange = item.family.accounts.create!(name: "Exchange", balance: 0, currency: "EUR", accountable: Crypto.new(subtype: "exchange"))++ assert_no_difference "AccountProvider.count" do+ post link_existing_account_trade_republic_items_url, params: { account_id: exchange.id, trade_republic_account_id: portfolio.id }+ end+ assert_equal I18n.t("trade_republic_items.link_existing_account.only_manual_investment"), flash[:alert]+ end+test "successful QR polling can complete without a phone number" doitem = families(:dylan_family).trade_republic_items.create!(name: "Trade Republic QR Connection",diff --git a/test/jobs/trade_republic_repair_job_test.rb b/test/jobs/trade_republic_repair_job_test.rbnew file mode 100644index 0000000000..df23e04a75--- /dev/null+++ b/test/jobs/trade_republic_repair_job_test.rb@@ -0,0 +1,20 @@+require "test_helper"++class TradeRepublicRepairJobTest < ActiveJob::TestCase+ test "skips provider accounts linked to a disabled account" do+ item = trade_republic_items(:configured_item)+ item.trade_republic_accounts.destroy_all+ provider_account = item.trade_republic_accounts.create!(+ name: "Trade Republic Crypto", kind: "crypto", trade_republic_account_id: "crypto:DE1", currency: "EUR"+ )+ account = item.family.accounts.create!(+ name: "Trade Republic Crypto", balance: 0, currency: "EUR", accountable: Crypto.new(subtype: "exchange")+ )+ provider_account.ensure_account_provider!(account)+ account.disable!++ TradeRepublicAccount::Processor.expects(:new).never++ TradeRepublicRepairJob.perform_now(item)+ end+enddiff --git a/test/migrations/normalize_trade_republic_activity_labels_migration_test.rb b/test/migrations/normalize_trade_republic_activity_labels_migration_test.rbnew file mode 100644index 0000000000..ba9643b2b6--- /dev/null+++ b/test/migrations/normalize_trade_republic_activity_labels_migration_test.rb@@ -0,0 +1,129 @@+# frozen_string_literal: true++require "test_helper"+require Rails.root.join("db/migrate/20260928090000_normalize_trade_republic_activity_labels")++class NormalizeTradeRepublicActivityLabelsMigrationTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @cash = @family.accounts.create!(+ name: "Trade Republic Cash", balance: 0, currency: "EUR", accountable: Depository.new(subtype: "checking")+ )+ @portfolio = @family.accounts.create!(+ name: "Trade Republic Portfolio", balance: 0, currency: "EUR", accountable: Investment.new(subtype: "brokerage")+ )+ end++ test "maps translated labels on investment accounts to fixed activity labels" do+ deposit = create_transaction(@portfolio, "Storting")+ interest = create_transaction(@portfolio, "Rente")+ fee = create_transaction(@portfolio, "Kaartkosten")++ run_migration++ assert_equal "Contribution", deposit.reload.investment_activity_label+ assert_equal "Interest", interest.reload.investment_activity_label+ assert_equal "Fee", fee.reload.investment_activity_label+ end++ test "clears deposit, withdrawal and card labels on the cash account" do+ transactions = [ "Storting", "Opname", "Kaartbetaling", "Card payment", "Belastingteruggaaf" ].map do |label|+ create_transaction(@cash, label)+ end++ run_migration++ transactions.each { |transaction| assert_nil transaction.reload.investment_activity_label }+ end++ test "maps a round up on the cash account to Buy" do+ round_up = create_transaction(@cash, "Round up")++ run_migration++ assert_equal "Buy", round_up.reload.investment_activity_label+ end++ test "clears English deposit and withdrawal labels the importer stored on the cash account" do+ withdrawal = create_transaction(@cash, "Withdrawal")+ deposit = create_transaction(@cash, "Contribution")++ run_migration++ assert_nil withdrawal.reload.investment_activity_label+ assert_nil deposit.reload.investment_activity_label+ end++ test "clears English cash labels when English is the only locale" do+ withdrawal = create_transaction(@cash, "Withdrawal")++ I18n.stubs(:available_locales).returns([ :en ])+ run_migration++ assert_nil withdrawal.reload.investment_activity_label+ end++ test "keeps English cash labels set by the user or a rule" do+ user_modified = create_transaction(@cash, "Withdrawal")+ user_modified.entry.update!(user_modified: true)+ locked = create_transaction(@cash, "Withdrawal")+ locked.lock_attr!(:investment_activity_label)+ rule_set = create_transaction(@cash, "Withdrawal")+ rule_set.data_enrichments.create!(attribute_name: "investment_activity_label", value: "Withdrawal", source: "rule")++ run_migration++ assert_equal "Withdrawal", user_modified.reload.investment_activity_label+ assert_equal "Withdrawal", locked.reload.investment_activity_label+ assert_equal "Withdrawal", rule_set.reload.investment_activity_label+ end++ test "keeps locked translated labels" do+ locked = create_transaction(@portfolio, "Storting")+ locked.lock_attr!(:investment_activity_label)++ run_migration++ assert_equal "Storting", locked.reload.investment_activity_label+ end++ test "leaves fixed labels, other providers and unknown values alone" do+ listed = create_transaction(@portfolio, "Withdrawal")+ other_provider = create_transaction(@cash, "Storting", source: "plaid")+ unknown = create_transaction(@cash, "Something else")++ run_migration++ assert_equal "Withdrawal", listed.reload.investment_activity_label+ assert_equal "Storting", other_provider.reload.investment_activity_label+ assert_equal "Something else", unknown.reload.investment_activity_label+ end++ test "can be run again" do+ deposit = create_transaction(@portfolio, "Storting")++ 2.times { run_migration }++ assert_equal "Contribution", deposit.reload.investment_activity_label+ end++ private++ def create_transaction(account, label, source: "trade_republic")+ account.entries.create!(+ name: "Entry",+ amount: -10,+ currency: "EUR",+ date: Date.current,+ source: source,+ external_id: SecureRandom.uuid,+ entryable: Transaction.new(investment_activity_label: label)+ ).transaction+ end++ def run_migration+ ActiveRecord::Migration.suppress_messages do+ NormalizeTradeRepublicActivityLabels.new.up+ end+ end+enddiff --git a/test/models/account_test.rb b/test/models/account_test.rbindex aa1d7bf9b4..c0df3dc108 100644--- a/test/models/account_test.rb+++ b/test/models/account_test.rb@@ -65,6 +65,19 @@ class AccountTest < ActiveSupport::TestCaseassert_equal expected_owner, owners.lastend+ test "set_current_balance schedules an account sync by default" do+ @account.expects(:sync_later).once++ assert @account.set_current_balance(1234).success?+ end++ test "set_current_balance skips the account sync when the caller schedules it" do+ @account.expects(:sync_later).never++ assert @account.set_current_balance(1234, schedule_sync: false).success?+ assert_equal 1234, @account.reload.current_anchor_balance+ end+test "create_and_sync calls sync_later by default" doAccount.any_instance.expects(:sync_later).oncediff --git a/test/models/trade_republic_account_activities_processor_test.rb b/test/models/trade_republic_account_activities_processor_test.rbindex f1d0506916..134f6df445 100644--- a/test/models/trade_republic_account_activities_processor_test.rb+++ b/test/models/trade_republic_account_activities_processor_test.rb@@ -22,14 +22,14 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCase@tr_account.reloadend- test "buy is imported as a trade with negative amount, never as spending income" do+ test "buy is imported as a trade that spends cash, never as spending income" doimport_event(order_execution_detail(quantity: "13.439945", isin: "US0378331005", amount: "2472.14"))trade = find_trade("trade_republic_event_evt_buy")assert_not_nil tradeassert_equal BigDecimal("13.439945"), trade.entryable.qtyassert_equal "Buy", trade.entryable.investment_activity_label- assert_equal BigDecimal("-2472.14"), trade.amount+ assert_equal BigDecimal("2472.14"), trade.amountendtest "crypto trades resolve to the same crypto security as crypto holdings" do@@ -178,7 +178,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_not @account.holdings.where(security: isin_security).exists?end- test "sell imports negative quantity and positive amount" do+ test "sell imports negative quantity and a cash inflow amount" doimport_event(order_execution_detail(event_id: "evt_sell",quantity: "-2.500000",@@ -190,7 +190,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_not_nil tradeassert_equal BigDecimal("-2.5"), trade.entryable.qtyassert_equal "Sell", trade.entryable.investment_activity_label- assert_equal BigDecimal("459.85"), trade.amount+ assert_equal BigDecimal("-459.85"), trade.amountendtest "trade derives a missing amount from quantity and price" do@@ -204,7 +204,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCasetrade = find_trade("trade_republic_event_evt_price_only")assert_not_nil tradeassert_equal BigDecimal("184.00"), trade.entryable.price- assert_equal BigDecimal("-460.00"), trade.amount+ assert_equal BigDecimal("460.00"), trade.amountendtest "syncing the same events twice creates no duplicates" do@@ -273,7 +273,42 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_equal "Buy", entry.trade.investment_activity_labelend- test "card events keep a card-specific activity label" do+ test "cash movements store canonical activity labels under a non-English locale" do+ I18n.with_locale(:nl) do+ @tr_account.update!(raw_timeline_payload: [+ deposit_event,+ { id: "evt_wd_nl", timestamp: "2026-08-01T10:00:00Z", category: "POC_CREATED", detail: { amount: "300.00", currency: "EUR" } },+ { id: "evt_interest_nl", timestamp: "2026-08-01T10:00:00Z", category: "INTEREST_PAYOUT_CREATED", detail: { amount: "1.20", currency: "EUR" } },+ { id: "evt_fee_nl", timestamp: "2026-08-01T10:00:00Z", eventType: "CARD_ORDER_FEE", category: "POC_CREATED", detail: { amount: "5.00", currency: "EUR" } }+ ])+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ end++ labels = %w[evt_dep evt_wd_nl evt_interest_nl evt_fee_nl].map do |id|+ Entry.find_by!(external_id: "trade_republic_event_#{id}").transaction.investment_activity_label+ end+ assert_equal %w[Contribution Withdrawal Interest Fee], labels+ assert_equal I18n.t("trade_republic_items.activities.labels.interest", locale: :nl),+ Entry.find_by!(external_id: "trade_republic_event_evt_interest_nl").name+ end++ test "cash account card, deposit and withdrawal activity carries no activity label under any locale" do+ cash_account, cash_sure = create_linked_cash_account!+ I18n.with_locale(:nl) do+ cash_account.update!(raw_timeline_payload: [+ deposit_event.merge(id: "evt_cash_dep_nl"),+ { id: "evt_cash_wd_nl", timestamp: "2026-08-01T10:00:00Z", category: "POC_CREATED", detail: { amount: "300.00", currency: "EUR" } },+ { id: "evt_cash_card_nl", timestamp: "2026-08-01T10:00:00Z", eventType: "CARD_TRANSACTION", category: "POC_CREATED", detail: { amount: "42.00", currency: "EUR" } }+ ])+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ end++ %w[evt_cash_dep_nl evt_cash_wd_nl evt_cash_card_nl].each do |id|+ assert_nil cash_sure.entries.find_by!(external_id: "trade_republic_event_#{id}").transaction.investment_activity_label, id+ end+ end++ test "card events are named after the card activity but carry no activity label" doimport_event({id: "evt_card_payment",timestamp: "2026-08-01T10:00:00Z",@@ -283,7 +318,8 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCase})entry = Entry.find_by(external_id: "trade_republic_event_evt_card_payment")- assert_equal "Card payment", entry.transaction.investment_activity_label+ assert_equal "Card payment", entry.name+ assert_nil entry.transaction.investment_activity_labelendtest "card cash back events that are purchases are imported as expenses with merchant details" do@@ -300,7 +336,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseentry = Entry.find_by(external_id: "trade_republic_event_evt_card_cash_back")assert_equal BigDecimal("204.18"), entry.amountassert_equal "Marktkauf", entry.name- assert_equal "Card payment", entry.transaction.investment_activity_label+ assert_nil entry.transaction.investment_activity_labelassert_equal "CARD_CASH_BACK", entry.transaction.extra.dig("trade_republic", "event_type")assert_equal "Card purchase", entry.transaction.extra.dig("trade_republic", "subtitle")end@@ -352,7 +388,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCasetrade = find_trade("trade_republic_event_evt_buy")assert_equal BigDecimal("511.96"), trade.entryable.priceassert_equal BigDecimal("1.00"), trade.entryable.fee- assert_equal BigDecimal("-1024.92"), trade.amount+ assert_equal BigDecimal("1024.92"), trade.amountassert_equal "1.00", trade.entryable.extra.dig("trade_republic", "fees")end@@ -382,7 +418,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_not_nil tradeassert_equal BigDecimal("511.96"), trade.entryable.priceassert_equal BigDecimal("1.00"), trade.entryable.fee- assert_equal BigDecimal("1022.92"), trade.amount+ assert_equal BigDecimal("-1022.92"), trade.amountassert_equal "Sell", trade.entryable.investment_activity_labelend@@ -397,7 +433,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCasetrade = find_trade("trade_republic_event_evt_sell_derive")assert_equal BigDecimal("511.96"), trade.entryable.priceassert_equal BigDecimal("1.00"), trade.entryable.fee- assert_equal BigDecimal("1022.92"), trade.amount+ assert_equal BigDecimal("-1022.92"), trade.amountendtest "buy and sell fallbacks include taxes alongside fees" do@@ -413,7 +449,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCasebuy = find_trade("trade_republic_event_evt_buy_tax")assert_equal BigDecimal("511.96"), buy.entryable.priceassert_equal BigDecimal("1.00"), buy.entryable.fee- assert_equal BigDecimal("-1025.42"), buy.amount # 2*511.96 + 1 + 0.50+ assert_equal BigDecimal("1025.42"), buy.amount # 2*511.96 + 1 + 0.50import_event(order_execution_detail(event_id: "evt_sell_tax",@@ -426,7 +462,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCase# Sell cash 1022.42 = gross - fee - tax → price (1022.42+1.50)/2assert_equal BigDecimal("511.96"), sell.entryable.priceassert_equal BigDecimal("1.00"), sell.entryable.fee- assert_equal BigDecimal("1022.42"), sell.amount+ assert_equal BigDecimal("-1022.42"), sell.amountendtest "reprocessing updates fee and share price on an existing trade" do@@ -532,7 +568,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_equal "Trade", trade.entryable_typeassert_equal BigDecimal("0.09329"), trade.entryable.qtyassert_equal "Buy", trade.entryable.investment_activity_label- assert_equal BigDecimal("-3.74"), trade.amount+ assert_equal BigDecimal("3.74"), trade.amountassert_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")@@ -552,17 +588,21 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_not_nil tradeassert_equal "Trade", trade.entryable_typeassert_equal BigDecimal("0.009977"), trade.entryable.qty- assert_equal BigDecimal("-0.40"), trade.amount+ assert_equal BigDecimal("0.40"), trade.amountassert_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_entryassert_equal "Transaction", cash_entry.entryable_typeassert_equal BigDecimal("0.40"), cash_entry.amount- assert_equal "Round up", cash_entry.transaction.investment_activity_label+ assert_equal "Buy", cash_entry.transaction.investment_activity_labelassert_equal "investment_contribution", cash_entry.transaction.kindassert_nil cash_entry.transaction.category_idassert_equal "SPARE_CHANGE_AGGREGATE", cash_entry.transaction.extra.dig("trade_republic", "event_type")++ counterpart = @account.entries.find_by!(external_id: "trade_republic_settlement_evt_round_up")+ assert_equal BigDecimal("-0.40"), counterpart.amount+ assert_equal counterpart.transaction, cash_entry.transaction.transfer.inflow_transactionendtest "round up and saveback remain idempotent across repeated processing" do@@ -617,7 +657,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCasecash_entry = Entry.find_by(account: cash_sure, external_id: "trade_republic_event_evt_round_up")assert_not_nil cash_entryassert_equal BigDecimal("0.40"), cash_entry.amount- assert_equal "Round up", cash_entry.transaction.investment_activity_label+ assert_equal "Buy", cash_entry.transaction.investment_activity_labelendtest "portfolio-only saveback and round up import as trades without cash entries" do@@ -753,6 +793,100 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert entry.reload.user_modified?end+ test "a linked Crypto account takes crypto trades and their settlements from the portfolio" do+ cash_account, cash_sure = create_linked_cash_account!+ stock = order_execution_detail(event_id: "evt_stock", quantity: "1", isin: "US0378331005", amount: "150.00")+ .deep_merge(detail: { signed_amount: -150.0 })+ bitcoin = order_execution_detail(event_id: "evt_btc", quantity: "0.000134", isin: "XF000BTC0017", amount: "11.00")+ .deep_merge(title: "Bitcoin", detail: { name: "Bitcoin", signed_amount: -11.0 })+ @tr_account.update!(raw_timeline_payload: [ stock, bitcoin ])+ process_all(@tr_account, cash_account)+ assert @account.entries.exists?(external_id: "trade_republic_settlement_evt_btc")++ crypto_account, crypto_sure = create_linked_crypto_account!+ process_all(@tr_account, crypto_account, cash_account)++ assert_equal %w[trade_republic_event_evt_stock trade_republic_settlement_evt_stock],+ @account.entries.order(:external_id).pluck(:external_id)+ assert_equal 0, @account.entries.sum(:amount)++ crypto_trade = crypto_sure.entries.find_by!(external_id: "trade_republic_event_evt_btc")+ assert_equal BigDecimal("11.0"), crypto_trade.amount+ counterpart = crypto_sure.entries.find_by!(external_id: "trade_republic_settlement_evt_btc")+ settlement = cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_btc")+ assert_equal counterpart.transaction, settlement.transaction.transfer.inflow_transaction+ assert_equal 0, crypto_sure.entries.sum(:amount)++ assert_no_difference [ -> { crypto_sure.entries.count }, -> { @account.entries.count }, -> { Transfer.count } ] do+ process_all(@tr_account, crypto_account, cash_account)+ end+ end++ test "an edited crypto trade stays on the portfolio when the Crypto account is linked" do+ bitcoin = order_execution_detail(event_id: "evt_btc", quantity: "0.000134", isin: "XF000BTC0017", amount: "11.00")+ import_event(bitcoin)+ edited = find_trade("trade_republic_event_evt_btc")+ edited.update!(user_modified: true)++ crypto_account, crypto_sure = create_linked_crypto_account!+ process_all(@tr_account, crypto_account)++ assert @account.entries.exists?(edited.id)+ assert_not crypto_sure.entries.exists?+ end++ test "a crypto trade with an edited settlement counterpart stays on the portfolio" do+ cash_account, _cash_sure = create_linked_cash_account!+ bitcoin = order_execution_detail(event_id: "evt_btc", quantity: "0.000134", isin: "XF000BTC0017", amount: "11.00")+ .deep_merge(detail: { signed_amount: -11.0 })+ @tr_account.update!(raw_timeline_payload: [ bitcoin ])+ process_all(@tr_account, cash_account)+ @account.entries.find_by!(external_id: "trade_republic_settlement_evt_btc").update!(user_modified: true)++ crypto_account, crypto_sure = create_linked_crypto_account!+ process_all(@tr_account, crypto_account, cash_account)++ assert find_trade("trade_republic_event_evt_btc")+ assert_not crypto_sure.entries.exists?+ end++ test "trades of a position listed under crypto go to the Crypto account whatever its ISIN" do+ @tr_account.update!(raw_positions_payload: [+ { "isin" => "XS0000000001", "name" => "Some Coin", "category" => "crypto_wallet", "quantity" => "1", "price" => "10" }+ ])+ coin = order_execution_detail(event_id: "evt_coin", quantity: "1", isin: "XS0000000001", amount: "10.00")+ @tr_account.update!(raw_timeline_payload: [ coin ])++ crypto_account, crypto_sure = create_linked_crypto_account!+ process_all(@tr_account, crypto_account)++ assert_not find_trade("trade_republic_event_evt_coin")+ assert crypto_sure.entries.exists?(external_id: "trade_republic_event_evt_coin")+ end++ test "trades of a closed crypto position stay on the Crypto account" do+ crypto_position = { "isin" => "XS0000000001", "name" => "Some Coin", "category" => "crypto_wallet", "quantity" => "1", "price" => "10" }+ coin = order_execution_detail(event_id: "evt_coin", quantity: "1", isin: "XS0000000001", amount: "10.00")+ @tr_account.update!(raw_positions_payload: [ crypto_position ], raw_timeline_payload: [ coin ])+ crypto_account, crypto_sure = create_linked_crypto_account!+ process_all(@tr_account, crypto_account)++ @tr_account.update!(raw_positions_payload: [])+ process_all(@tr_account)+ assert_not find_trade("trade_republic_event_evt_coin")++ process_all(crypto_account)+ assert crypto_sure.entries.exists?(external_id: "trade_republic_event_evt_coin")+ end++ test "crypto trades stay on the portfolio while the Crypto account is unlinked" do+ @item.trade_republic_accounts.create!(name: "Crypto", kind: "crypto", trade_republic_account_id: "crypto:DEPROC1", currency: "EUR")++ import_event(order_execution_detail(event_id: "evt_btc", quantity: "0.000134", isin: "XF000BTC0017", amount: "11.00"))++ assert find_trade("trade_republic_event_evt_btc")+ end+test "split accounts settle buys and sells against the cash account" docash_account, cash_sure = create_linked_cash_account!buy = order_execution_detail(event_id: "evt_settle_buy", quantity: "2.0", isin: "IE00B5BMR087", amount: "1024.92")@@ -764,8 +898,8 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseTradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).processTradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process- assert_equal BigDecimal("-1024.92"), find_trade("trade_republic_event_evt_settle_buy").amount- assert_equal 0, @account.entries.where(entryable_type: "Transaction").count+ assert_equal BigDecimal("1024.92"), find_trade("trade_republic_event_evt_settle_buy").amount+ assert_equal 2, @account.entries.where(entryable_type: "Transaction").countbuy_cash = cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_settle_buy")assert_equal BigDecimal("1024.92"), buy_cash.amount@@ -780,9 +914,84 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_equal "funds_movement", sell_cash.transaction.kindassert_nil sell_cash.transaction.category_id- assert_no_difference -> { cash_sure.entries.count } do+ buy_counterpart = @account.entries.find_by!(external_id: "trade_republic_settlement_evt_settle_buy")+ assert_equal BigDecimal("-1024.92"), buy_counterpart.amount+ assert_equal buy_cash.date, buy_counterpart.date+ assert_equal "Transfer from #{cash_sure.name}", buy_counterpart.name+ assert_equal "funds_movement", buy_counterpart.transaction.kind+ assert_equal "Transfer", buy_counterpart.transaction.investment_activity_label+ buy_transfer = buy_cash.transaction.transfer+ assert buy_transfer.confirmed?+ assert_equal buy_counterpart.transaction, buy_transfer.inflow_transaction+ assert_equal buy_cash.transaction, buy_transfer.outflow_transaction++ sell_counterpart = @account.entries.find_by!(external_id: "trade_republic_settlement_evt_settle_sell")+ assert_equal BigDecimal("529.0"), sell_counterpart.amount+ assert_equal "Transfer to #{cash_sure.name}", sell_counterpart.name+ sell_transfer = sell_cash.transaction.transfer+ assert_equal sell_cash.transaction, sell_transfer.inflow_transaction+ assert_equal sell_counterpart.transaction, sell_transfer.outflow_transaction++ # Each trade's cash impact is offset by its counterpart, so the+ # portfolio's own cash stays at zero.+ assert_equal 0, @account.entries.sum(:amount)++ assert_no_difference [ -> { cash_sure.entries.count }, -> { @account.entries.count }, -> { Transfer.count } ] do+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).processTradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).processend+ assert_equal buy_transfer, buy_cash.transaction.reload.transfer+ end++ test "settlement counterpart is removed with its trade and never relinked after the user unlinks it" do+ cash_account, cash_sure = create_linked_cash_account!+ buy = order_execution_detail(event_id: "evt_counterpart", quantity: "2.0", isin: "IE00B5BMR087", amount: "1024.92")+ @tr_account.update!(raw_timeline_payload: [ buy ])++ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ cash_entry = cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_counterpart")+ counterpart = @account.entries.find_by!(external_id: "trade_republic_settlement_evt_counterpart")++ cash_entry.transaction.transfer.reject!+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ assert_nil cash_entry.transaction.reload.transfer+ assert_nil counterpart.transaction.reload.transfer++ @tr_account.update!(raw_timeline_payload: [ buy.merge(deleted: true) ])+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_not @account.entries.exists?(external_id: "trade_republic_settlement_evt_counterpart")+ assert_not cash_sure.entries.exists?(external_id: "trade_republic_event_evt_counterpart")+ end++ test "cash settlement without a portfolio trade books no counterpart" do+ cash_account, cash_sure = create_linked_cash_account!+ buy = order_execution_detail(event_id: "evt_no_trade", quantity: "2.0", isin: "IE00B5BMR087", amount: "1024.92")+ @tr_account.update!(raw_timeline_payload: [ buy ])++ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ cash_entry = cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_no_trade")+ assert_nil cash_entry.transaction.transfer+ assert_not @account.entries.exists?(external_id: "trade_republic_settlement_evt_no_trade")+ end++ test "cash settlement in another currency than the portfolio books no counterpart" do+ cash_account, cash_sure = create_linked_cash_account!+ buy = order_execution_detail(event_id: "evt_other_currency", quantity: "2.0", isin: "IE00B5BMR087", amount: "1024.92")+ @tr_account.update!(raw_timeline_payload: [ buy ])+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process+ @account.update!(currency: "USD")++ assert_difference -> { DebugLogEntry.where(level: "warn", account: @account).count }, 1 do+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process+ end++ cash_entry = cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_other_currency")+ assert_nil cash_entry.transaction.transfer+ assert_not @account.entries.exists?(external_id: "trade_republic_settlement_evt_other_currency")endtest "cash settlement is skipped when the trade direction is unknown" do@@ -822,7 +1031,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_not cash_sure.entries.exists?(external_id: "trade_republic_event_evt_settle_stale")end- test "cash account deposits are fund movements, not investment contributions" do+ test "cash account deposits are standard transactions, not transfers or investment contributions" docash_account, cash_sure = create_linked_cash_account!wallet_top_up = deposit_event.merge(id: "evt_google_pay", eventType: "PAYMENT_INBOUND_GOOGLE_PAY", title: "Cash in")bank_credit = deposit_event.merge(id: "evt_bank_credit", eventType: "BANK_TRANSACTION_INCOMING", title: "Employer")@@ -831,7 +1040,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseTradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).processtop_up = cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_google_pay").transaction- assert_equal "funds_movement", top_up.kind+ assert_equal "standard", top_up.kindassert_nil top_up.category_idcredit = cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_bank_credit").transaction@@ -860,11 +1069,127 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseTradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).processlegacy.transaction.reload- assert_equal "funds_movement", legacy.transaction.kind+ assert_equal "standard", legacy.transaction.kindassert_nil legacy.transaction.category_idassert_nil legacy.transaction.investment_activity_labelend+ test "keeps a rule-assigned category and label on a deposit that earlier syncs stored as an investment contribution" do+ cash_account, cash_sure = create_linked_cash_account!+ category = @family.investment_contributions_category+ legacy = Account::ProviderImportAdapter.new(cash_sure).import_transaction(+ external_id: "trade_republic_event_evt_rule_legacy",+ amount: BigDecimal("-500.00"),+ currency: "EUR",+ date: Date.parse("2026-08-01"),+ name: "Cash in",+ source: "trade_republic",+ kind: "investment_contribution"+ )+ assert_nil legacy.transaction.category_id+ assert legacy.transaction.enrich_attribute(:category_id, category.id, source: "rule")+ assert legacy.transaction.enrich_attribute(:investment_activity_label, "Contribution", source: "rule")++ cash_account.update!(raw_timeline_payload: [+ deposit_event.merge(id: "evt_rule_legacy", eventType: "PAYMENT_INBOUND_GOOGLE_PAY", title: "Cash in")+ ])+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ legacy.transaction.reload+ assert_equal "standard", legacy.transaction.kind+ assert_equal category.id, legacy.transaction.category_id+ assert_equal "Contribution", legacy.transaction.investment_activity_label+ end++ test "resets payments that earlier syncs stored as fund movements" do+ cash_account, cash_sure = create_linked_cash_account!+ adapter = Account::ProviderImportAdapter.new(cash_sure)+ deposit = adapter.import_transaction(+ external_id: "trade_republic_event_evt_legacy_in", amount: BigDecimal("-2000.00"), currency: "EUR",+ date: Date.parse("2026-08-01"), name: "Niels Eulink", source: "trade_republic", kind: "funds_movement"+ )+ withdrawal = adapter.import_transaction(+ external_id: "trade_republic_event_evt_legacy_out", amount: BigDecimal("300.00"), currency: "EUR",+ date: Date.parse("2026-08-01"), name: "Payout", source: "trade_republic", kind: "funds_movement"+ )++ cash_account.update!(raw_timeline_payload: [+ deposit_event.merge(id: "evt_legacy_in", eventType: "PAYMENT_INBOUND", title: "Niels Eulink", detail: { amount: "2000.00", currency: "EUR" }),+ { id: "evt_legacy_out", timestamp: "2026-08-01T10:00:00Z", eventType: "PAYMENT_OUTBOUND", category: "POC_CREATED",+ title: "Payout", detail: { amount: "300.00", currency: "EUR" } }+ ])+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_equal "standard", deposit.transaction.reload.kind+ assert_equal "standard", withdrawal.transaction.reload.kind+ end++ test "keeps fund movements of matched transfers, edited rows and sale settlements" do+ cash_account, cash_sure = create_linked_cash_account!+ bank = @family.accounts.create!(name: "Bank", balance: 0, currency: "EUR", accountable: Depository.new)+ adapter = Account::ProviderImportAdapter.new(cash_sure)+ matched = adapter.import_transaction(+ external_id: "trade_republic_event_evt_matched", amount: BigDecimal("-2000.00"), currency: "EUR",+ date: Date.parse("2026-08-01"), name: "Cash in", source: "trade_republic", kind: "funds_movement"+ )+ bank_outflow = bank.entries.create!(+ name: "To Trade Republic", amount: 2000, currency: "EUR", date: Date.parse("2026-08-01"),+ entryable: Transaction.new(kind: "funds_movement")+ )+ Transfer.create!(inflow_transaction: matched.transaction, outflow_transaction: bank_outflow.transaction)+ edited = adapter.import_transaction(+ external_id: "trade_republic_event_evt_edited", amount: BigDecimal("-100.00"), currency: "EUR",+ date: Date.parse("2026-08-01"), name: "Cash in", source: "trade_republic", kind: "funds_movement"+ )+ edited.update!(user_modified: true)++ sell = order_execution_detail(event_id: "evt_sell_keep", quantity: "-1", isin: "US0378331005", amount: "150.00")+ @tr_account.update!(raw_timeline_payload: [ sell ])+ cash_account.update!(raw_timeline_payload: [+ deposit_event.merge(id: "evt_matched", eventType: "PAYMENT_INBOUND_GOOGLE_PAY", detail: { amount: "2000.00", currency: "EUR" }),+ deposit_event.merge(id: "evt_edited", eventType: "PAYMENT_INBOUND_GOOGLE_PAY", detail: { amount: "100.00", currency: "EUR" })+ ])+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_equal "funds_movement", matched.transaction.reload.kind+ assert_equal "funds_movement", edited.transaction.reload.kind+ assert_equal "funds_movement", cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_sell_keep").transaction.kind+ end++ test "keeps the settlement kind on a sale that earlier syncs stored as an investment contribution" do+ cash_account, cash_sure = create_linked_cash_account!+ legacy = Account::ProviderImportAdapter.new(cash_sure).import_transaction(+ external_id: "trade_republic_event_evt_legacy_sell", amount: BigDecimal("-150.00"), currency: "EUR",+ date: Date.parse("2026-08-01"), name: "Apple", source: "trade_republic", kind: "investment_contribution"+ )+ assert_equal "investment_contribution", legacy.transaction.kind++ sell = order_execution_detail(event_id: "evt_legacy_sell", quantity: "-1", isin: "US0378331005", amount: "150.00")+ @tr_account.update!(raw_timeline_payload: [ sell ])+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ assert_equal "funds_movement", legacy.transaction.reload.kind+ end++ test "a standard deposit is matched to the bank transfer that funded it" do+ cash_account, cash_sure = create_linked_cash_account!+ bank = @family.accounts.create!(name: "Bank", balance: 0, currency: "EUR", accountable: Depository.new)+ bank_outflow = bank.entries.create!(+ name: "To Trade Republic", amount: 2000, currency: "EUR", date: Date.parse("2026-08-01"),+ entryable: Transaction.new+ )+ cash_account.update!(raw_timeline_payload: [+ deposit_event.merge(id: "evt_funded", eventType: "PAYMENT_INBOUND", detail: { amount: "2000.00", currency: "EUR" })+ ])+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process++ @family.auto_match_transfers!++ deposit = cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_funded").transaction+ assert_equal bank_outflow.transaction, deposit.transfer&.outflow_transaction+ assert_equal "funds_movement", deposit.reload.kind+ end+test "keeps a rule-assigned investment contributions category and label on cash account deposits" docash_account, cash_sure = create_linked_cash_account!category = @family.investment_contributions_category@@ -902,7 +1227,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseassert_equal "Trade", trade.entryable_typeassert_equal BigDecimal("0.25"), trade.entryable.qtyassert_equal "Buy", trade.entryable.investment_activity_label- assert_equal BigDecimal("-25.00"), trade.amount+ assert_equal BigDecimal("25.00"), trade.amountassert_equal "SAVINGS_PLAN_INVOICE_CREATED", trade.entryable.extra.dig("trade_republic", "event_type")cash_entry = Entry.find_by!(account: cash_sure, external_id: "trade_republic_event_evt_savings_plan")@@ -982,7 +1307,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCasetrade = find_trade("trade_republic_event_evt_savings_plan")assert_not_nil tradeassert_equal BigDecimal("0.25"), trade.entryable.qty- assert_equal BigDecimal("-25.00"), trade.amount+ assert_equal BigDecimal("25.00"), trade.amountendtest "executed card payments import while declined cards are skipped" do@@ -1178,7 +1503,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseendend- test "Google Pay inbound deposits import as fund movements" do+ test "Google Pay inbound deposits import as standard deposits" docash_account, cash_sure = create_linked_cash_account!cash_account.update!(raw_timeline_payload: [ {id: "evt_gpay",@@ -1192,7 +1517,7 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseentry = Entry.find_by!(account: cash_sure, external_id: "trade_republic_event_evt_gpay")assert_equal BigDecimal("-50.00"), entry.amount- assert_equal "funds_movement", entry.transaction.kind+ assert_equal "standard", entry.transaction.kindassert_nil entry.transaction.investment_activity_labelend@@ -1295,6 +1620,30 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCaseprivate+ def create_linked_crypto_account!+ crypto_provider = @item.trade_republic_accounts.create!(+ name: "Crypto",+ kind: "crypto",+ trade_republic_account_id: "crypto:DEPROC1",+ currency: "EUR"+ )+ crypto_sure = @family.accounts.create!(+ name: "Trade Republic Crypto",+ balance: 0,+ cash_balance: 0,+ currency: "EUR",+ accountable: Crypto.new(subtype: "exchange")+ )+ crypto_provider.ensure_account_provider!(crypto_sure)+ [ crypto_provider.reload, crypto_sure ]+ end++ def process_all(*trade_republic_accounts)+ trade_republic_accounts.each do |trade_republic_account|+ TradeRepublicAccount::ActivitiesProcessor.new(trade_republic_account.reload).process+ end+ end+def create_linked_cash_account!cash_provider = @item.trade_republic_accounts.create!(name: "Cash",diff --git a/test/models/trade_republic_account_holdings_processor_test.rb b/test/models/trade_republic_account_holdings_processor_test.rbindex d2f39a9aa6..d0a8299813 100644--- a/test/models/trade_republic_account_holdings_processor_test.rb+++ b/test/models/trade_republic_account_holdings_processor_test.rb@@ -542,6 +542,34 @@ class TradeRepublicAccountHoldingsProcessorTest < ActiveSupport::TestCaseassert_equal [ "CRYPTO:BTC" ], @account.holdings.includes(:security).map { |holding| holding.security.ticker }end+ test "crypto positions move to the linked Crypto account" do+ @tr_account.update!(+ holdings_snapshot_complete: true,+ current_balance: 270,+ raw_positions_payload: [+ position_payload(isin: "US0378331005", quantity: "2", price: "100"),+ position_payload(isin: "XF000BTC0017", quantity: "0.001", price: "70000").merge("category" => "crypto_wallet")+ ]+ )+ TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload).process+ assert_equal 2, @account.holdings.count++ crypto = @item.trade_republic_accounts.create!(+ name: "Crypto", kind: "crypto", trade_republic_account_id: "crypto:DEHOLD1", currency: "EUR", current_balance: 70+ )+ crypto_sure = @family.accounts.create!(+ name: "Trade Republic Crypto", balance: 0, cash_balance: 0, currency: "EUR", accountable: Crypto.new(subtype: "exchange")+ )+ crypto.ensure_account_provider!(crypto_sure)+ TradeRepublicAccount::HoldingsProcessor.new(@tr_account.reload).process+ TradeRepublicAccount::HoldingsProcessor.new(crypto.reload).process++ assert_equal [ "US0378331005" ], @account.holdings.map { |holding| holding.security.ticker }+ assert_equal [ "XF000BTC0017" ], crypto_sure.holdings.map { |holding| holding.security.ticker }+ assert_equal BigDecimal("200"), @tr_account.account_balance+ assert_equal BigDecimal("70"), crypto.account_balance+ end+privatedef import_position(isin:, quantity:, price:, average_cost: nil, symbol: nil, exchange_slug: nil)diff --git a/test/models/trade_republic_account_processor_test.rb b/test/models/trade_republic_account_processor_test.rbnew file mode 100644index 0000000000..8b0c2302d2--- /dev/null+++ b/test/models/trade_republic_account_processor_test.rb@@ -0,0 +1,22 @@+require "test_helper"++class TradeRepublicAccountProcessorTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper++ test "sets the current balance anchor without scheduling an account sync" do+ provider_account = trade_republic_accounts(:cash_account)+ account = provider_account.trade_republic_item.family.accounts.create!(+ name: "TR Cash", balance: 0, currency: "EUR", accountable: Depository.new+ )+ provider_account.ensure_account_provider!(account)++ assert_no_difference -> { account.syncs.count } do+ assert_no_enqueued_jobs only: SyncJob do+ TradeRepublicAccount::Processor.new(provider_account.reload).process+ end+ end++ assert account.reload.has_current_anchor?+ assert_equal BigDecimal("500"), account.current_anchor_balance.to_d+ end+enddiff --git a/test/models/trade_republic_item_importer_test.rb b/test/models/trade_republic_item_importer_test.rbindex 4a0956f407..c25aff62f2 100644--- a/test/models/trade_republic_item_importer_test.rb+++ b/test/models/trade_republic_item_importer_test.rb@@ -39,6 +39,44 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCaseassert_equal 1, account.raw_positions_payload.sizeend+ test "import creates a Crypto account valued at the crypto positions" do+ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(client_result(+ "status" => "ok",+ "account" => { "brokerage_account_id" => "DE9997", "currency" => "EUR" },+ "cash" => { "amount" => "10", "currency" => "EUR" },+ "positions" => [+ { "isin" => "US0378331005", "name" => "Apple Inc.", "category" => "brokerage", "quantity" => "2", "price" => "100" },+ { "isin" => "XF000BTC0017", "name" => "Bitcoin", "category" => "crypto_wallet", "quantity" => "0.001", "price" => "70000" }+ ],+ "events" => [],+ "warnings" => []+ ))++ TradeRepublicItem::Importer.new(@item, provider: provider).import++ crypto = @item.trade_republic_accounts.find_by(kind: "crypto")+ assert_equal "crypto:DE9997", crypto.trade_republic_account_id+ assert_equal BigDecimal("70"), crypto.current_balance+ assert_equal BigDecimal("270"), @item.trade_republic_accounts.find_by(kind: "portfolio").current_balance+ end++ test "import creates no Crypto account without crypto" do+ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(client_result(+ "status" => "ok",+ "account" => { "brokerage_account_id" => "DE9996", "currency" => "EUR" },+ "cash" => { "amount" => "10", "currency" => "EUR" },+ "positions" => [ { "isin" => "US0378331005", "name" => "Apple Inc.", "quantity" => "2", "price" => "100" } ],+ "events" => [],+ "warnings" => []+ ))++ TradeRepublicItem::Importer.new(@item, provider: provider).import++ assert_not @item.trade_republic_accounts.exists?(kind: "crypto")+ end+test "cash balance keeps funds reserved for open orders" doprovider = mock("trade_republic_provider")provider.expects(:sync).returns(client_result(diff --git a/test/models/trade_republic_item_syncer_test.rb b/test/models/trade_republic_item_syncer_test.rbindex db750be964..45e2f69088 100644--- a/test/models/trade_republic_item_syncer_test.rb+++ b/test/models/trade_republic_item_syncer_test.rb@@ -1,6 +1,8 @@require "test_helper"class TradeRepublicItemSyncerTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper+setup do@item = trade_republic_items(:configured_item)end@@ -53,6 +55,31 @@ class TradeRepublicItemSyncerTest < ActiveSupport::TestCaseassert_not_nil @item.trade_republic_accounts.find_by(trade_republic_account_id: "DESYNC1")end+ test "sync schedules one account sync per account under the item sync" do+ family = @item.family+ accounts = {+ trade_republic_accounts(:main_account) => family.accounts.create!(+ name: "TR Portfolio", balance: 0, currency: "EUR", accountable: Investment.new+ ),+ trade_republic_accounts(:cash_account) => family.accounts.create!(+ name: "TR Cash", balance: 0, currency: "EUR", accountable: Depository.new+ )+ }+ accounts.each { |provider_account, account| provider_account.ensure_account_provider!(account) }+ @item.stubs(:import_latest_data).returns({})+ sync = Sync.create!(syncable: @item)++ assert_enqueued_jobs 2, only: SyncJob do+ TradeRepublicItem::Syncer.new(@item).perform_sync(sync)+ end++ accounts.each do |provider_account, account|+ assert_equal [ sync.id ], account.syncs.pluck(:parent_id)+ assert account.reload.has_current_anchor?+ assert_equal provider_account.account_balance.to_d, account.current_anchor_balance.to_d+ end+ end+privatedef client_result(data)