Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Import IBKR withholding tax, interest and fees, and keep dividend signs (#5033)

arnaurodondev443f8ba67a6b
diff --git a/app/models/ibkr_account/activities_processor.rb b/app/models/ibkr_account/activities_processor.rb
index 744ea68998..6499fe77ed 100644
--- a/app/models/ibkr_account/activities_processor.rb
+++ b/app/models/ibkr_account/activities_processor.rb
@@ -1,7 +1,26 @@
class IbkrAccount::ActivitiesProcessor
include IbkrAccount::DataHelpers
- SUPPORTED_CASH_TRANSACTION_TYPES = [ "DEPOSITS/WITHDRAWALS", "DIVIDENDS" ].freeze
+ # Flex `CashTransaction` types, upper-cased, and the label each is booked
+ # with: fees are a Fee, interest is Interest, a payment in lieu is a
+ # Dividend. Withholding tax carries the label of the income it was withheld
+ # from (see cash_transaction_label), so dividends read net, as Trade
+ # Republic books them. Every one keeps the sign IBKR gives it, so a
+ # reversal, a refund or interest paid on margin moves cash the way it did at
+ # IBKR.
+ CASH_TRANSACTION_LABELS = {
+ "DIVIDENDS" => "Dividend",
+ "PAYMENT IN LIEU OF DIVIDENDS" => "Dividend",
+ "WITHHOLDING TAX" => "Dividend",
+ "OTHER FEES" => "Fee",
+ "COMMISSION ADJUSTMENTS" => "Fee",
+ "BROKER INTEREST RECEIVED" => "Interest",
+ "BROKER INTEREST PAID" => "Interest",
+ "BOND INTEREST RECEIVED" => "Interest",
+ "BOND INTEREST PAID" => "Interest"
+ }.freeze
+
+ SUPPORTED_CASH_TRANSACTION_TYPES = [ "DEPOSITS/WITHDRAWALS", *CASH_TRANSACTION_LABELS.keys ].freeze
def initialize(ibkr_account)
@ibkr_account = ibkr_account
@@ -18,7 +37,10 @@ class IbkrAccount::ActivitiesProcessor
trades_count = trade_results.count { |r| r[:imported] }
fee_count = trade_results.sum { |r| r[:fees] }
- cash_count = cash_transactions.sum { |t| process_cash_transaction(t.with_indifferent_access) ? 1 : 0 }
+ @cash_transactions = cash_transactions.map(&:with_indifferent_access)
+ @skipped_cash_types = Hash.new(0)
+ cash_count = @cash_transactions.sum { |t| process_cash_transaction(t) ? 1 : 0 }
+ capture_skipped_cash_types
{ trades: trades_count, transactions: cash_count + fee_count }
end
@@ -227,30 +249,73 @@ class IbkrAccount::ActivitiesProcessor
def supported_cash_transaction?(row)
type = row[:type].to_s.upcase.strip
- return false unless SUPPORTED_CASH_TRANSACTION_TYPES.include?(type)
+ unless SUPPORTED_CASH_TRANSACTION_TYPES.include?(type)
+ amount = parse_decimal(row[:amount])
+ @skipped_cash_types[row[:type].to_s.strip] += 1 if amount.present? && !amount.zero?
+ return false
+ end
return false unless row[:transaction_id].present? && row[:amount].present? && row[:currency].present? && row[:report_date].present?
return false unless fx_rate_available?(row)
- type != "DIVIDENDS" || row[:conid].present?
+ type == "WITHHOLDING TAX" || CASH_TRANSACTION_LABELS[type] != "Dividend" || row[:conid].present?
end
- # supported_cash_transaction? ensures only known types reach here; no else branch needed
+ # supported_cash_transaction? ensures only known types reach here.
+ # IBKR's amount is negative for money out, Sure's is positive.
def classify_cash_transaction(row, amount)
type = row[:type].to_s.upcase.strip
case type
when "DEPOSITS/WITHDRAWALS"
amount.positive? ? [ "Contribution", -amount.abs ] : [ "Withdrawal", amount.abs ]
- when "DIVIDENDS"
- [ "Dividend", -amount.abs ]
+ else
+ [ cash_transaction_label(row, type), -amount ]
end
end
+ # Tax withheld on a security's dividend reduces that dividend. Without a
+ # conid it was withheld on credit interest, and on a bond it was withheld
+ # from the coupon; both reduce the interest.
+ def cash_transaction_label(row, type)
+ return "Interest" if type == "WITHHOLDING TAX" && (row[:conid].blank? || bond_withholding?(row))
+
+ CASH_TRANSACTION_LABELS[type]
+ end
+
+ # The row's asset category says so when the query includes it; otherwise a
+ # bond interest row for the same conid in the statement does.
+ def bond_withholding?(row)
+ return true if row[:asset_category].to_s.upcase.strip == "BOND"
+
+ @cash_transactions.any? do |other|
+ other[:conid].to_s == row[:conid].to_s && other[:type].to_s.upcase.strip.start_with?("BOND INTEREST")
+ end
+ end
+
+ # A skipped row with an amount is cash the account no longer accounts for.
+ def capture_skipped_cash_types
+ return if @skipped_cash_types.empty?
+
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "warn",
+ message: "Skipped IBKR cash transactions of unsupported types",
+ source: self.class.name,
+ provider_key: "ibkr",
+ account_provider: @ibkr_account.account_provider,
+ family: @ibkr_account.ibkr_item&.family,
+ metadata: { ibkr_account_id: @ibkr_account.id, skipped_cash_transaction_types: @skipped_cash_types }
+ )
+ end
+
def build_cash_transaction_name(row, label, security = nil)
- return label unless label == "Dividend"
+ type = row[:type].to_s.upcase.strip
+ return label if type == "DEPOSITS/WITHDRAWALS"
+
+ ticker = security&.ticker || security_symbol_for_conid(row[:conid])
+ return "Dividend from #{ticker || row[:conid]}" if type == "DIVIDENDS"
- ticker = security&.ticker || security_symbol_for_conid(row[:conid]) || row[:conid]
- "Dividend from #{ticker}"
+ [ row[:type].to_s.strip, ticker ].compact.join(" for ")
end
def resolve_security_for_cash_transaction(row)
diff --git a/config/locales/views/settings/providers/ca.yml b/config/locales/views/settings/providers/ca.yml
index 39149c5245..34f162834b 100644
--- a/config/locales/views/settings/providers/ca.yml
+++ b/config/locales/views/settings/providers/ca.yml
@@ -141,8 +141,7 @@ ca:
cash_transactions: 'Cash Transactions:'
cash_transactions_fields: 'Fields: Amount, Conid, Currency, FX Rate To Base,
Report Date, Transaction ID, Type'
- cash_transactions_options: 'Options: Dividends, Deposits & Withdrawals,
- Detail'
+ cash_transactions_options: 'Options: Dividends, Deposits & Withdrawals, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Detail'
change_in_position_value_summary: 'Change In Position Value Summary: Currency,
End Of Period Value'
net_asset_value: 'Net Asset Value (NAV) in Base:'
diff --git a/config/locales/views/settings/providers/de.yml b/config/locales/views/settings/providers/de.yml
index b3cf89bcde..6de46b2846 100644
--- a/config/locales/views/settings/providers/de.yml
+++ b/config/locales/views/settings/providers/de.yml
@@ -132,7 +132,7 @@ de:
cash_report_options: 'Optionen: keine'
cash_transactions: 'Cash Transactions:'
cash_transactions_fields: 'Felder: Amount, Conid, Currency, FX Rate To Base, Report Date, Transaction ID, Type'
- cash_transactions_options: 'Optionen: Dividends, Deposits & Withdrawals, Detail'
+ cash_transactions_options: 'Optionen: Dividends, Deposits & Withdrawals, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Detail'
change_in_position_value_summary: 'Change In Position Value Summary: Currency, End Of Period Value'
net_asset_value: 'Net Asset Value (NAV) in Base:'
net_asset_value_fields: 'Felder: Currency, Report Date, Total'
diff --git a/config/locales/views/settings/providers/en.yml b/config/locales/views/settings/providers/en.yml
index 05943707cb..ab9b3cd18a 100644
--- a/config/locales/views/settings/providers/en.yml
+++ b/config/locales/views/settings/providers/en.yml
@@ -306,7 +306,7 @@ en:
cash_report_options: "Options: None"
cash_report_fields: "Fields: Currency, Ending Cash"
cash_transactions: "Cash Transactions:"
- cash_transactions_options: "Options: Dividends, Deposits & Withdrawals, Detail"
+ cash_transactions_options: "Options: Deposits & Withdrawals, Dividends, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Detail"
cash_transactions_fields: "Fields: Amount, Conid, Currency, FX Rate To Base, Report Date, Transaction ID, Type"
change_in_position_value_summary: "Change In Position Value Summary: Currency, End Of Period Value"
net_asset_value: "Net Asset Value (NAV) in Base:"
diff --git a/config/locales/views/settings/providers/es.yml b/config/locales/views/settings/providers/es.yml
index 03ff75888e..a08f45927b 100644
--- a/config/locales/views/settings/providers/es.yml
+++ b/config/locales/views/settings/providers/es.yml
@@ -229,7 +229,7 @@ es:
cash_report_options: 'Opciones: ninguna'
cash_report_fields: 'Campos: Currency, Ending Cash'
cash_transactions: 'Cash Transactions:'
- cash_transactions_options: 'Opciones: Dividends, Deposits & Withdrawals, Detail'
+ cash_transactions_options: 'Opciones: Dividends, Deposits & Withdrawals, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Detail'
cash_transactions_fields: 'Campos: Amount, Conid, Currency, FX Rate To Base, Report Date, Transaction ID, Type'
change_in_position_value_summary: 'Change In Position Value Summary: Currency, End Of Period Value'
net_asset_value: 'Net Asset Value (NAV) in Base:'
diff --git a/config/locales/views/settings/providers/fr.yml b/config/locales/views/settings/providers/fr.yml
index af5f1bba9d..880ad90445 100644
--- a/config/locales/views/settings/providers/fr.yml
+++ b/config/locales/views/settings/providers/fr.yml
@@ -169,7 +169,7 @@ fr:
cash_report_options: "Options : None"
cash_transactions: "Cash Transactions :"
cash_transactions_fields: "Fields : Amount, Conid, Currency, FX Rate To Base, Report Date, Transaction ID, Type"
- cash_transactions_options: "Options : Dividends, Deposits & Withdrawals, Detail"
+ cash_transactions_options: "Options : Dividends, Deposits & Withdrawals, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Detail"
change_in_position_value_summary: "Change In Position Value Summary : Currency, End Of Period Value"
net_asset_value: "Net Asset Value (NAV) in Base :"
net_asset_value_fields: "Fields : Currency, Report Date, Total"
diff --git a/config/locales/views/settings/providers/hu.yml b/config/locales/views/settings/providers/hu.yml
index 8d474c05c5..6773478c2d 100644
--- a/config/locales/views/settings/providers/hu.yml
+++ b/config/locales/views/settings/providers/hu.yml
@@ -216,7 +216,7 @@ hu:
cash_report_options: "Opciók: Nincs"
cash_report_fields: "Mezők: Pénznem, Záró készpénz"
cash_transactions: "Készpénztranzakciók:"
- cash_transactions_options: "Opciók: Osztalékok, Befizetések és kifizetések, Részletek"
+ cash_transactions_options: "Opciók: Osztalékok, Befizetések és kifizetések, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Részletek"
cash_transactions_fields: "Mezők: Összeg, Conid, Pénznem, FX-árfolyam alaphoz, Jelentési dátum, Tranzakció-azonosító, Típus"
change_in_position_value_summary: "Pozícióérték változásának összefoglalója: Pénznem, Időszak végi érték"
net_asset_value: "Nettó eszközérték (NAV) alapban:"
diff --git a/config/locales/views/settings/providers/it.yml b/config/locales/views/settings/providers/it.yml
index 9c7ceaa167..28b0049026 100644
--- a/config/locales/views/settings/providers/it.yml
+++ b/config/locales/views/settings/providers/it.yml
@@ -228,7 +228,7 @@ it:
cash_report_options: "Opzioni: Nessuna"
cash_report_fields: "Campi: Valuta, Liquidità finale"
cash_transactions: "Transazioni liquidità:"
- cash_transactions_options: "Opzioni: Dividendi, Depositi e prelievi, Dettaglio"
+ cash_transactions_options: "Opzioni: Dividendi, Depositi e prelievi, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Dettaglio"
cash_transactions_fields: "Campi: Importo, Conid, Valuta, Tasso FX alla base, Data rapporto, ID transazione, Tipo"
change_in_position_value_summary: "Riepilogo variazione valore posizione: Valuta, Valore fine periodo"
net_asset_value: "Valore patrimoniale netto (NAV) in base:"
diff --git a/config/locales/views/settings/providers/nl.yml b/config/locales/views/settings/providers/nl.yml
index a9bdad0f9e..cd9cce480f 100644
--- a/config/locales/views/settings/providers/nl.yml
+++ b/config/locales/views/settings/providers/nl.yml
@@ -305,7 +305,7 @@ nl:
cash_report_options: "Opties: geen"
cash_report_fields: "Velden: Currency, Ending Cash"
cash_transactions: "Cash Transactions:"
- cash_transactions_options: "Opties: Dividends, Deposits & Withdrawals, Detail"
+ cash_transactions_options: "Opties: Dividends, Deposits & Withdrawals, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Detail"
cash_transactions_fields: "Velden: Amount, Conid, Currency, FX Rate To Base, Report Date, Transaction ID, Type"
change_in_position_value_summary: "Change In Position Value Summary: Currency, End Of Period Value"
net_asset_value: "Net Asset Value (NAV) in Base:"
diff --git a/config/locales/views/settings/providers/pl.yml b/config/locales/views/settings/providers/pl.yml
index cf77090bd8..2364005c9a 100644
--- a/config/locales/views/settings/providers/pl.yml
+++ b/config/locales/views/settings/providers/pl.yml
@@ -152,8 +152,7 @@ pl:
cash_transactions: 'Cash Transactions:'
cash_transactions_fields: 'Fields: Amount, Conid, Currency, FX Rate To Base,
Report Date, Transaction ID, Type'
- cash_transactions_options: 'Options: Dividends, Deposits & Withdrawals,
- Detail'
+ cash_transactions_options: 'Options: Dividends, Deposits & Withdrawals, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Detail'
change_in_position_value_summary: 'Change In Position Value Summary: Currency,
End Of Period Value'
net_asset_value: 'Net Asset Value (NAV) in Base:'
diff --git a/config/locales/views/settings/providers/pt-PT.yml b/config/locales/views/settings/providers/pt-PT.yml
index 0a1ab23048..2405824075 100644
--- a/config/locales/views/settings/providers/pt-PT.yml
+++ b/config/locales/views/settings/providers/pt-PT.yml
@@ -251,7 +251,7 @@ pt-PT:
cash_report_options: "Opções: None"
cash_report_fields: "Campos: Currency, Ending Cash"
cash_transactions: "Transações de Numerário:"
- cash_transactions_options: "Opções: Dividends, Deposits & Withdrawals, Detail"
+ cash_transactions_options: "Opções: Dividends, Deposits & Withdrawals, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Detail"
cash_transactions_fields: "Campos: Amount, Conid, Currency, FX Rate To Base, Report Date, Transaction ID, Type"
change_in_position_value_summary: "Alteração no Resumo do Valor da Posição: Currency, End Of Period Value"
net_asset_value: "Valor Líquido dos Ativos (NAV) em Base:"
diff --git a/config/locales/views/settings/providers/ru.yml b/config/locales/views/settings/providers/ru.yml
index 0ba1255758..7c6024da65 100644
--- a/config/locales/views/settings/providers/ru.yml
+++ b/config/locales/views/settings/providers/ru.yml
@@ -149,7 +149,7 @@ ru:
cash_transactions: 'Операции с наличными:'
cash_transactions_fields: 'Поля: Сумма, Conid, Валюта, Курс к базовой валюте,
Дата отчёта, ID операции, Тип'
- cash_transactions_options: 'Опции: Дивиденды, Депозиты и снятия, Детали'
+ cash_transactions_options: 'Опции: Дивиденды, Депозиты и снятия, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Детали'
change_in_position_value_summary: 'Изменение стоимости позиции: Валюта,
Стоимость на конец периода'
net_asset_value: 'Чистая стоимость активов (NAV) в базовой валюте:'
diff --git a/config/locales/views/settings/providers/tr.yml b/config/locales/views/settings/providers/tr.yml
index 34521b8602..f947ffc3fb 100644
--- a/config/locales/views/settings/providers/tr.yml
+++ b/config/locales/views/settings/providers/tr.yml
@@ -147,8 +147,7 @@ tr:
cash_transactions: 'Nakit İşlemleri:'
cash_transactions_fields: 'Alanlar: Amount, Conid, Currency, FX Rate To
Base, Report Date, Transaction ID, Type'
- cash_transactions_options: 'Seçenekler: Dividends, Deposits & Withdrawals,
- Detail'
+ cash_transactions_options: 'Seçenekler: Dividends, Deposits & Withdrawals, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Detail'
change_in_position_value_summary: 'Pozisyon Değeri Değişim Özeti: Currency,
End Of Period Value'
net_asset_value: 'Ana Para Biriminde Net Varlık Değeri (NAV):'
diff --git a/config/locales/views/settings/providers/uk.yml b/config/locales/views/settings/providers/uk.yml
index 8a95c2cc7e..8c36a4d27a 100644
--- a/config/locales/views/settings/providers/uk.yml
+++ b/config/locales/views/settings/providers/uk.yml
@@ -243,7 +243,7 @@ uk:
cash_report_options: "Опції: Немає"
cash_report_fields: "Поля: Валюта, Кінцева готівка"
cash_transactions: "Готівкові транзакції:"
- cash_transactions_options: "Опції: Дивіденди, Депозити та зняття, Детально"
+ cash_transactions_options: "Опції: Дивіденди, Депозити та зняття, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Детально"
cash_transactions_fields: "Поля: Сума, Conid, Валюта, Курс FX до базової, Дата звіту, ID транзакції, Тип"
change_in_position_value_summary: "Зведення про зміну вартості позиції: Валюта, Вартість на кінець періоду"
net_asset_value: "Чиста вартість активів (NAV) у базовій валюті:"
diff --git a/config/locales/views/settings/providers/vi.yml b/config/locales/views/settings/providers/vi.yml
index 000d8e45eb..071433bbcc 100644
--- a/config/locales/views/settings/providers/vi.yml
+++ b/config/locales/views/settings/providers/vi.yml
@@ -218,7 +218,7 @@ vi:
cash_report_options: "Tùy chọn: Không"
cash_report_fields: "Trường: Tiền tệ, Tiền mặt cuối kỳ"
cash_transactions: "Giao dịch tiền mặt:"
- cash_transactions_options: "Tùy chọn: Cổ tức, Nạp/Rút, Chi tiết"
+ cash_transactions_options: "Tùy chọn: Cổ tức, Nạp/Rút, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Chi tiết"
cash_transactions_fields: "Trường: Số tiền, Conid, Tiền tệ, Tỷ giá FX sang Cơ sở, Ngày báo cáo, ID giao dịch, Loại"
change_in_position_value_summary: "Tóm tắt thay đổi giá trị vị thế: Tiền tệ, Giá trị cuối kỳ"
net_asset_value: "Giá trị tài sản ròng (NAV) theo Cơ sở:"
diff --git a/config/locales/views/settings/providers/zh-CN.yml b/config/locales/views/settings/providers/zh-CN.yml
index bedc0450ee..a69d7a9361 100644
--- a/config/locales/views/settings/providers/zh-CN.yml
+++ b/config/locales/views/settings/providers/zh-CN.yml
@@ -405,7 +405,7 @@ zh-CN:
cash_report_options: 选项:无
cash_report_fields: 字段:Currency、Ending Cash
cash_transactions: 现金交易:
- cash_transactions_options: 选项:Dividends、Deposits & Withdrawals、Detail
+ cash_transactions_options: 选项:Dividends、Deposits & Withdrawals、Payment In Lieu Of Dividends、Withholding Tax、Broker Interest Paid、Broker Interest Received、Bond Interest Paid、Bond Interest Received、Other Fees、Commission Adjustments、Detail
cash_transactions_fields: 字段:Amount、Conid、Currency、FX Rate To Base、Report Date、Transaction ID、Type
change_in_position_value_summary: 仓位价值变动汇总:Currency、End Of Period Value
net_asset_value: 基础币种下的净资产值(NAV):
diff --git a/config/locales/views/settings/providers/zh-TW.yml b/config/locales/views/settings/providers/zh-TW.yml
index 5addb45e84..4234f8fa04 100644
--- a/config/locales/views/settings/providers/zh-TW.yml
+++ b/config/locales/views/settings/providers/zh-TW.yml
@@ -231,7 +231,7 @@ zh-TW:
cash_report_options: 選項:None
cash_report_fields: 欄位:Currency, Ending Cash
cash_transactions: Cash Transactions:
- cash_transactions_options: 選項:Dividends, Deposits & Withdrawals, Detail
+ cash_transactions_options: 選項:Dividends, Deposits & Withdrawals, Payment In Lieu Of Dividends, Withholding Tax, Broker Interest Paid, Broker Interest Received, Bond Interest Paid, Bond Interest Received, Other Fees, Commission Adjustments, Detail
cash_transactions_fields: 欄位:Amount, Conid, Currency, FX Rate To Base, Report Date, Transaction ID, Type
change_in_position_value_summary: Change In Position Value Summary:Currency, End Of Period Value
net_asset_value: Net Asset Value (NAV) in Base:
diff --git a/test/fixtures/files/ibkr/flex_statement.xml b/test/fixtures/files/ibkr/flex_statement.xml
index ffc2c5f7fe..c86c16751a 100644
--- a/test/fixtures/files/ibkr/flex_statement.xml
+++ b/test/fixtures/files/ibkr/flex_statement.xml
@@ -24,6 +24,7 @@
<CashTransactions>
<CashTransaction transactionID="4001" type="Deposits/Withdrawals" amount="500.00" currency="CHF" fxRateToBase="1" reportDate="2026-05-03" />
<CashTransaction transactionID="4002" type="Dividends" amount="2.50" currency="USD" fxRateToBase="0.91" reportDate="2026-05-04" conid="265598" />
+ <CashTransaction transactionID="4003" type="Withholding Tax" amount="-0.38" currency="USD" fxRateToBase="0.91" reportDate="2026-05-04" conid="265598" />
</CashTransactions>
</FlexStatement>
<FlexStatement accountId="U7654321" fromDate="2025-05-08" toDate="2026-05-08" whenGenerated="2026-05-08;12:00:00">
diff --git a/test/models/ibkr_account_processor_test.rb b/test/models/ibkr_account_processor_test.rb
index 07ea33e537..c139f77d6e 100644
--- a/test/models/ibkr_account_processor_test.rb
+++ b/test/models/ibkr_account_processor_test.rb
@@ -250,6 +250,130 @@ class IbkrAccountProcessorTest < ActiveSupport::TestCase
assert_nil @account.entries.find_by(external_id: "ibkr_trade_fee_1001"), "the commission is not counted again beside it"
end
+ # Each keeps IBKR's sign: negative there is money out, positive in Sure.
+ test "processor imports withholding tax, interest, fees and payments in lieu" do
+ set_cash_transactions(
+ cash_row("5001", "Withholding Tax", "-0.38", conid: "265598"),
+ cash_row("5002", "Withholding Tax", "0.10", conid: "265598"),
+ cash_row("5003", "Payment In Lieu Of Dividends", "1.20", conid: "265598"),
+ cash_row("5004", "Broker Interest Received", "1.00"),
+ cash_row("5005", "Broker Interest Paid", "-2.00"),
+ cash_row("5006", "Bond Interest Received", "3.00"),
+ cash_row("5007", "Bond Interest Paid", "-0.50"),
+ cash_row("5008", "Other Fees", "-10.00"),
+ cash_row("5009", "Commission Adjustments", "0.25"),
+ cash_row("5010", "Withholding Tax", "-0.20")
+ )
+
+ IbkrAccount::Processor.new(@ibkr_account).process
+
+ expected = {
+ "5001" => [ "Dividend", "0.38", "Withholding Tax for #{securities(:aapl).ticker}" ],
+ "5002" => [ "Dividend", "-0.10", "Withholding Tax for #{securities(:aapl).ticker}" ],
+ "5003" => [ "Dividend", "-1.20", "Payment In Lieu Of Dividends for #{securities(:aapl).ticker}" ],
+ "5004" => [ "Interest", "-1.00", "Broker Interest Received" ],
+ "5005" => [ "Interest", "2.00", "Broker Interest Paid" ],
+ "5006" => [ "Interest", "-3.00", "Bond Interest Received" ],
+ "5007" => [ "Interest", "0.50", "Bond Interest Paid" ],
+ "5008" => [ "Fee", "10.00", "Other Fees" ],
+ "5009" => [ "Fee", "-0.25", "Commission Adjustments" ],
+ "5010" => [ "Interest", "0.20", "Withholding Tax" ]
+ }
+
+ expected.each do |transaction_id, (label, amount, name)|
+ entry = @account.entries.find_by(external_id: "ibkr_cash_#{transaction_id}")
+ assert_not_nil entry, "cash transaction #{transaction_id} was not imported"
+ assert_equal label, entry.entryable.investment_activity_label, transaction_id
+ assert_equal BigDecimal(amount), entry.amount, transaction_id
+ assert_equal name, entry.name, transaction_id
+ assert_equal "USD", entry.currency, transaction_id
+ end
+
+ withholding = @account.entries.find_by(external_id: "ibkr_cash_5001").entryable
+ assert_equal securities(:aapl).id, withholding.extra["security_id"]
+ assert_equal "Withholding Tax", withholding.extra.dig("ibkr", "type")
+ end
+
+ # Trade Republic books dividends net of the tax withheld; IBKR reports the
+ # tax as a row of its own, which nets into the dividend through its label.
+ test "withholding tax reduces dividend income" do
+ set_cash_transactions(
+ cash_row("6101", "Dividends", "2.50", conid: "265598"),
+ cash_row("6102", "Withholding Tax", "-0.38", conid: "265598")
+ )
+
+ IbkrAccount::Processor.new(@ibkr_account).process
+
+ totals = InvestmentStatement::Totals.new(@family, account_ids: [ @account.id ], date_range: Date.current..Date.current).call
+ assert_equal BigDecimal("2.12"), totals[:dividends]
+ end
+
+ # IBKR cancels a dividend with a negative Dividends row and books it again,
+ # so the reversal is money out and the income nets to the rebooked amount.
+ test "a dividend reversal is booked as money out" do
+ set_cash_transactions(
+ cash_row("6001", "Dividends", "2.50", conid: "265598"),
+ cash_row("6002", "Dividends", "-2.50", conid: "265598"),
+ cash_row("6003", "Dividends", "2.40", conid: "265598")
+ )
+
+ IbkrAccount::Processor.new(@ibkr_account).process
+
+ amounts = %w[6001 6002 6003].map { |id| @account.entries.find_by(external_id: "ibkr_cash_#{id}").amount }
+ assert_equal [ BigDecimal("-2.5"), BigDecimal("2.5"), BigDecimal("-2.4") ], amounts
+
+ totals = InvestmentStatement::Totals.new(@family, account_ids: [ @account.id ], date_range: Date.current..Date.current).call
+ assert_equal BigDecimal("2.4"), totals[:dividends]
+ end
+
+ test "an unsupported cash transaction type is skipped" do
+ set_cash_transactions(cash_row("7001", "Price Adjustments", "-1.00"))
+
+ assert_nothing_raised { IbkrAccount::Processor.new(@ibkr_account).process }
+
+ assert_nil @account.entries.find_by(external_id: "ibkr_cash_7001")
+ end
+
+ # A skipped row with an amount is cash the account lost track of, so support
+ # needs to see it; one entry per run, not one per row.
+ test "skipped cash transaction types with an amount are captured for support" do
+ set_cash_transactions(
+ cash_row("7101", "Price Adjustments", "-1.00"),
+ cash_row("7102", "Price Adjustments", "-2.00"),
+ cash_row("7103", "Advisor Fees", "-3.00"),
+ cash_row("7104", "Something Else", "0")
+ )
+
+ assert_difference -> { DebugLogEntry.where(provider_key: "ibkr").count }, 1 do
+ IbkrAccount::Processor.new(@ibkr_account).process
+ end
+
+ entry = DebugLogEntry.where(provider_key: "ibkr").last
+ assert_equal "warn", entry.level
+ assert_equal @family, entry.family
+ assert_equal @ibkr_account.account_provider, entry.account_provider
+ assert_equal({ "Price Adjustments" => 2, "Advisor Fees" => 1 }, entry.metadata["skipped_cash_transaction_types"])
+ end
+
+ # Tax withheld from a bond coupon carries the bond's conid, but it reduces
+ # the coupon's interest, not dividends.
+ test "withholding tax on a bond coupon reduces interest" do
+ set_cash_transactions(
+ cash_row("6201", "Bond Interest Received", "3.00", conid: "9001"),
+ cash_row("6202", "Withholding Tax", "-0.30", conid: "9001"),
+ cash_row("6203", "Withholding Tax", "-0.10", conid: "9002", asset_category: "BOND")
+ )
+
+ IbkrAccount::Processor.new(@ibkr_account).process
+
+ assert_equal "Interest", @account.entries.find_by(external_id: "ibkr_cash_6202").entryable.investment_activity_label
+ assert_equal "Interest", @account.entries.find_by(external_id: "ibkr_cash_6203").entryable.investment_activity_label
+
+ totals = InvestmentStatement::Totals.new(@family, account_ids: [ @account.id ], date_range: Date.current..Date.current).call
+ assert_equal BigDecimal("0"), totals[:dividends]
+ assert_equal BigDecimal("2.60"), totals[:interest]
+ end
+
test "processor computes weighted provider cost basis for grouped lots" do
@ibkr_account.update!(
raw_holdings_payload: [
@@ -382,6 +506,25 @@ class IbkrAccountProcessorTest < ActiveSupport::TestCase
private
+ def cash_row(transaction_id, type, amount, conid: nil, asset_category: nil)
+ {
+ "transaction_id" => transaction_id,
+ "type" => type,
+ "amount" => amount,
+ "currency" => "USD",
+ "fx_rate_to_base" => "1",
+ "report_date" => Date.current.to_s,
+ "conid" => conid,
+ "asset_category" => asset_category
+ }.compact
+ end
+
+ def set_cash_transactions(*rows)
+ payload = @ibkr_account.reload.raw_activities_payload.deep_dup
+ payload["cash_transactions"] = rows
+ @ibkr_account.update!(raw_activities_payload: payload)
+ end
+
def set_commission_currency(trade_id, currency)
payload = @ibkr_account.reload.raw_activities_payload.deep_dup
payload["trades"].find { |trade| trade["trade_id"] == trade_id }["ib_commission_currency"] = currency
diff --git a/test/models/ibkr_item_importer_test.rb b/test/models/ibkr_item_importer_test.rb
index c91d967e5d..127fd49c14 100644
--- a/test/models/ibkr_item_importer_test.rb
+++ b/test/models/ibkr_item_importer_test.rb
@@ -26,7 +26,7 @@ class IbkrItemImporterTest < ActiveSupport::TestCase
assert_equal 2, primary_account.raw_equity_summary_payload.size
assert_equal 1, primary_account.raw_holdings_payload.size
assert_equal 2, primary_account.raw_activities_payload["trades"].size
- assert_equal 2, primary_account.raw_activities_payload["cash_transactions"].size
+ assert_equal 3, primary_account.raw_activities_payload["cash_transactions"].size
end
test "raises parse error for malformed flex statement xml" do
diff --git a/test/models/ibkr_item_report_parser_test.rb b/test/models/ibkr_item_report_parser_test.rb
index b2c252221b..7a73937fb6 100644
--- a/test/models/ibkr_item_report_parser_test.rb
+++ b/test/models/ibkr_item_report_parser_test.rb
@@ -15,7 +15,9 @@ class IbkrItemReportParserTest < ActiveSupport::TestCase
assert_equal 2, first_account[:equity_summary_in_base].size
assert_equal 1, first_account[:open_positions].size
assert_equal 2, first_account[:trades].size
- assert_equal 2, first_account[:cash_transactions].size
+ assert_equal 3, first_account[:cash_transactions].size
+ assert_equal "Withholding Tax", first_account[:cash_transactions].last["type"]
+ assert_equal "-0.38", first_account[:cash_transactions].last["amount"]
second_account = parsed[:accounts].second
assert_equal "U7654321", second_account[:ibkr_account_id]