The personal finance app for everyone (by everyone)
Ruby
Expose trade fees, stored rates and activity fields in the API and export (#5048)
arnaurodondev6cd5114eb94c
diff --git a/app/models/family/data_exporter.rb b/app/models/family/data_exporter.rbindex 06048d6376..b0bd29d610 100644--- a/app/models/family/data_exporter.rb+++ b/app/models/family/data_exporter.rb@@ -425,7 +425,7 @@ class Family::DataExporter:tags,entry: [:account,- { child_entries: { entryable: :tags } }+ { child_entries: [ :account, { entryable: :tags } ] }]).find_each do |transaction|transaction_data = {@@ -442,6 +442,13 @@ class Family::DataExportermerchant_id: transaction.merchant_id,tag_ids: transaction.tag_ids,kind: transaction.kind,+ # Safe reads of what importers keep in extra; the payload itself is+ # not exported.+ investment_activity_label: transaction.investment_activity_label,+ provider_type: transaction.provider_type,+ security_id: transaction.serializable_security_id,+ exchange_rate: transaction.numeric_exchange_rate,+ amount_currency: transaction.entry.currency,created_at: transaction.created_at,updated_at: transaction.updated_at}@@ -511,6 +518,13 @@ class Family::DataExporterprice: trade.price,amount: trade.entry.amount,currency: trade.currency,+ fee: trade.fee,+ investment_activity_label: trade.investment_activity_label,+ exchange_rate: trade.numeric_exchange_rate,+ # The cost basis applies exchange_rate from currency (the+ # trade's), the cash balance from amount_currency (the entry's),+ # which can differ from it.+ amount_currency: trade.entry.currency,lot_total_cost: lot_total_costs[trade.entry.id],lot_source_trade_id: trade.lot_source_entry&.entryable_id,created_at: trade.created_at,@@ -621,6 +635,11 @@ class Family::DataExportermerchant_id: transaction.merchant_id,tag_ids: transaction.tag_ids,kind: transaction.kind,+ investment_activity_label: transaction.investment_activity_label,+ provider_type: transaction.provider_type,+ security_id: transaction.serializable_security_id,+ exchange_rate: transaction.numeric_exchange_rate,+ amount_currency: child_entry.currency,created_at: transaction.created_at,updated_at: transaction.updated_at}diff --git a/app/models/trade.rb b/app/models/trade.rbindex e2a61032ef..cc33300601 100644--- a/app/models/trade.rb+++ b/app/models/trade.rb@@ -44,6 +44,34 @@ class Trade < ApplicationRecordextra&.dig("exchange_rate")end+ # The stored exchange rate as a number, read the way Money#exchange_to reads+ # it (to_d), or nil when the app would not use it. The app applies it on two+ # paths: the cost basis (Holding::TradeCalculatorHelpers) converts price and+ # fee from trade.currency, and the cash balance (Balance::SyncCache) converts+ # entry.amount_money from entry.currency. The two currencies are the same+ # unless the web form or PATCH /api/v1/trades/:id changed entry.currency,+ # which leaves trade.currency as it was. So the rate is returned when either+ # currency differs from the account's, and is nil when none is stored, it is+ # not a positive number that survives the conversion to Float, or both are+ # the account's currency. The API and the data export read this, so a+ # malformed value written straight into extra, or an extra that is not a+ # hash, cannot break them.+ def numeric_exchange_rate+ return nil unless extra.is_a?(Hash)++ value = extra["exchange_rate"]+ return nil unless value.is_a?(Numeric) || value.is_a?(String)++ account_currency = entry&.account&.currency.to_s.upcase+ return nil if account_currency.blank?++ foreign = [ currency, entry&.currency ].compact_blank.map(&:upcase)+ return nil unless foreign.any? { |code| code != account_currency }++ rate = value.to_d.to_f+ rate if rate.finite? && rate.positive?+ end+def exchange_rate=(value)if value.blank?self.extra = (extra || {}).merge("exchange_rate" => nil, "exchange_rate_invalid" => false)diff --git a/app/models/transaction.rb b/app/models/transaction.rbindex b5c07a99aa..536907a55a 100644--- a/app/models/transaction.rb+++ b/app/models/transaction.rb@@ -105,6 +105,26 @@ class Transaction < ApplicationRecordextra&.dig("exchange_rate")end+ # The stored exchange rate as a number, read the way Money#exchange_to reads+ # it (to_d), or nil when the app would not use it: none is stored, it is not+ # a positive number that survives the conversion to Float, or the row is+ # already in the account's currency. The API and the data export read this,+ # so a malformed value written straight into extra, or an extra that is not+ # a hash, cannot break them.+ def numeric_exchange_rate+ return nil unless extra.is_a?(Hash)++ value = extra["exchange_rate"]+ return nil unless value.is_a?(Numeric) || value.is_a?(String)++ entry_currency = entry&.currency.to_s.upcase+ account_currency = entry&.account&.currency.to_s.upcase+ return nil if entry_currency.blank? || account_currency.blank? || entry_currency == account_currency++ rate = value.to_d.to_f+ rate if rate.finite? && rate.positive?+ end+def exchange_rate=(value)if value.blank?self.extra = (extra || {}).merge("exchange_rate" => nil, "exchange_rate_invalid" => false)@@ -564,7 +584,31 @@ class Transaction < ApplicationRecordenddef activity_security_id- extra&.dig("security_id").presence || extra&.dig("security", "id").presence+ return nil unless extra.is_a?(Hash)++ nested_security = extra["security"]+ extra["security_id"].presence || (nested_security["id"].presence if nested_security.is_a?(Hash))+ end++ UUID_FORMAT = /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/++ # activity_security_id as the API and the data export emit it: a uuid+ # string, or nil when extra holds anything else under the key.+ def serializable_security_id+ id = activity_security_id+ id if id.is_a?(String) && id.match?(UUID_FORMAT)+ end++ # The provider's own type for this row, such as IBKR's "Withholding Tax",+ # read from extra[<entry source>]["type"] where importers keep it. Only this+ # string is exposed; the rest of the provider payload stays internal.+ def provider_type+ source = entry&.source+ return nil if source.blank? || !extra.is_a?(Hash)++ payload = extra[source]+ type = payload["type"] if payload.is_a?(Hash)+ type.presence if type.is_a?(String)enddef activity_securitydiff --git a/app/views/api/v1/trades/_trade.json.jbuilder b/app/views/api/v1/trades/_trade.json.jbuilderindex 05d15e4e75..9f751cf197 100644--- a/app/views/api/v1/trades/_trade.json.jbuilder+++ b/app/views/api/v1/trades/_trade.json.jbuilder@@ -9,6 +9,21 @@ json.notes trade.entry.notesjson.qty trade.qtyjson.price trade.price_money.formatjson.investment_activity_label trade.investment_activity_label+# The fee charged on the trade, formatted like price, and as an unrounded,+# locale-independent decimal string (the stored value).+json.fee trade.fee_money.format+json.fee_decimal trade.fee.to_s("F")+# The rate to the account's currency stored on the trade, for example by a+# provider that reports its own rate. The cost basis applies it to price and+# fee, from `currency` (the trade's); the cash balance applies it to `amount`,+# from amount_currency (the entry's). The two are the same unless the web form+# or PATCH changed the entry's currency, which leaves the trade's as it was.+# The rate was recorded for `currency`; the cash balance then reuses it+# unchanged for amount_currency.+# Null when the trade carries none, in which case market rates are used, and+# when both currencies are the account's.+json.exchange_rate trade.numeric_exchange_rate+json.amount_currency trade.entry.currencyjson.lot_source_trade_id trade.lot_source_entry&.entryable_idjson.account dodiff --git a/app/views/api/v1/transactions/_transaction.json.jbuilder b/app/views/api/v1/transactions/_transaction.json.jbuilderindex 9c39d2775a..86f071d6eb 100644--- a/app/views/api/v1/transactions/_transaction.json.jbuilder+++ b/app/views/api/v1/transactions/_transaction.json.jbuilder@@ -40,6 +40,19 @@ json.classification transaction.entry.classification# Transaction::BUDGET_EXCLUDED_KINDS are left out entirely.json.kind transaction.kind+# Investment activity on a brokerage cash row (Dividend, Interest, Fee, ...),+# plus a few fields importers keep in extra. Only these specific values are+# exposed, never the provider payload itself: the provider's own type for the+# row (e.g. "Withholding Tax"), the Sure security the row relates to, and the+# rate from the row's currency to the account's currency stored on it.+# amount_currency is the currency of the amount, which that rate converts+# from, the same as `currency` here.+json.investment_activity_label transaction.investment_activity_label+json.provider_type transaction.provider_type+json.security_id transaction.serializable_security_id+json.exchange_rate transaction.numeric_exchange_rate+json.amount_currency transaction.entry.currency+# Excluded entries are left out of budget and report totals, and splitting# marks the parent excluded. A split parent's amount is carried by its# children, so a client summing a list should skip the parent. entries.excludeddiff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex 2e65e3f29b..78d0f06027 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -1985,6 +1985,33 @@ components:type: booleandescription: Whether the transaction has been split; its amount is thencarried by its split children.+ investment_activity_label:+ type: string+ nullable: true+ description: Investment activity of a brokerage cash row, such as Dividend,+ Interest or Fee+ provider_type:+ type: string+ nullable: true+ description: The importing provider's type for the row, such as IBKR's "Withholding+ Tax", when one is recorded. For CoinSpot, Sure sets it from the kind of+ movement.+ security_id:+ type: string+ format: uuid+ nullable: true+ description: Sure security the row relates to (for example the one that+ paid a dividend), when the importer recorded it. GET /api/v1/securities/{id}+ finds it only if an account holds or has traded it.+ exchange_rate:+ type: number+ nullable: true+ description: Rate from the transaction's currency to the account's currency+ stored on it. Null when none is stored or the transaction is in the account's+ currency.+ amount_currency:+ type: string+ description: Currency of the amount, always the same as currency on a transaction.account:"$ref": "#/components/schemas/Account"category:@@ -3229,6 +3256,28 @@ components:investment_activity_label:type: stringnullable: true+ fee:+ type: string+ description: Fee charged on the trade, formatted like price+ fee_decimal:+ type: string+ description: Fee as the exact stored, unrounded, locale-independent decimal+ string. A purchase fee adds to the cost and a sale fee comes off the proceeds+ exchange_rate:+ type: number+ nullable: true+ description: Rate to the account's currency stored on the trade, such as+ one reported by the provider. The cost basis applies it to price and fee,+ from currency; the cash balance applies it to amount, from amount_currency.+ The two match unless an edit changed only the amount's currency. It was+ recorded for currency; when amount_currency differs, the cash balance+ reuses it unchanged. Null when none is stored or both currencies are the+ account's.+ amount_currency:+ type: string+ description: Currency of the trade's amount (the entry's), which the cash+ balance converts from with exchange_rate. It can differ from currency,+ the trade's own.lot_source_trade_id:type: stringformat: uuiddiff --git a/docs/api/transactions.md b/docs/api/transactions.mdindex bc30caf353..32f3b7e1d7 100644--- a/docs/api/transactions.md+++ b/docs/api/transactions.md@@ -77,6 +77,11 @@ A transaction response includes:"kind": "standard","excluded": false,"split_parent": false,+ "investment_activity_label": null,+ "provider_type": null,+ "security_id": null,+ "exchange_rate": null,+ "amount_currency": "USD","account": {"id": "uuid","name": "Checking Account",@@ -117,6 +122,18 @@ A transaction response includes:| `excluded` | `true` when the transaction is left out of budget and report totals. || `split_parent` | `true` when the transaction has been split. Splitting a transaction marks it excluded, and its split children carry the amount. |+### Investment activity and provider fields++These are `null` on most transactions. They are set on brokerage cash rows, such as dividends, interest, fees and withholding tax, by the providers that record them.++| Field | Description |+| --- | --- |+| `investment_activity_label` | The investment activity of the row, such as `Dividend`, `Interest` or `Fee`. |+| `provider_type` | The importing provider's type for the row, for example IBKR's `"Withholding Tax"`. Use it to tell rows apart that share a label. IBKR, Trading 212, Wise, Akahu and Kraken store the provider's own type. For CoinSpot, Sure sets it from the kind of movement, such as `"receive"` or `"send"`. Only this value is exposed; the provider's raw payload is not. |+| `security_id` | The id of the Sure security the row relates to, such as the one that paid a dividend, or `null`. `GET /api/v1/securities/{id}` finds it only when one of your accounts holds or has traded that security; otherwise that lookup returns 404. |+| `exchange_rate` | The rate from the transaction's currency to the account's currency stored on the row, such as one reported by the provider. `null` when none is stored, and when the transaction is in the account's currency, since no conversion applies. |+| `amount_currency` | The currency of the amount. On a transaction it is always the same as `currency`, which `exchange_rate` converts from. |+### Linking to a transaction`id` identifies the transaction in the API. Web routes for a single transaction take the id of its entry instead, so use `entry_id` to link into the app, for example `/transactions/{entry_id}`.diff --git a/spec/requests/api/v1/trades_spec.rb b/spec/requests/api/v1/trades_spec.rbindex 1ec10b9f85..d0dfcadc08 100644--- a/spec/requests/api/v1/trades_spec.rb+++ b/spec/requests/api/v1/trades_spec.rb@@ -70,19 +70,23 @@ RSpec.describe 'API V1 Trades', type: :request do)end+ # A EUR trade in the USD account, with a fee and a stored rate, so the+ # documented fee, exchange_rate and amount_currency fields are populated.let!(:trade) dotrade_record = Trade.new(security: security,qty: 100,price: 250.50,- currency: 'USD',+ fee: 1.25,+ currency: 'EUR',+ exchange_rate: 1.08,investment_activity_label: 'Buy')entry = account.entries.create!(name: 'Buy 100 shares of VTI',date: Date.current,- amount: 25_050,- currency: 'USD',+ amount: 25_051.25,+ currency: 'EUR',entryable: trade_record)entry.entryablediff --git a/spec/requests/api/v1/transactions_spec.rb b/spec/requests/api/v1/transactions_spec.rbindex 0c9f88a94f..2b7d101dab 100644--- a/spec/requests/api/v1/transactions_spec.rb+++ b/spec/requests/api/v1/transactions_spec.rb@@ -95,6 +95,30 @@ RSpec.describe 'API V1 Transactions', type: :request doentry.transactionend+ # An imported EUR dividend in the USD account, so the documented+ # investment_activity_label, provider_type, security_id, exchange_rate and+ # amount_currency fields are populated.+ let!(:dividend_transaction) do+ security = Security.create!(ticker: 'VTI', name: 'Vanguard Total Stock Market ETF', country_code: 'US')+ entry = account.entries.create!(+ name: 'Dividend VTI',+ date: Date.current - 2.days,+ amount: -12.40,+ currency: 'EUR',+ source: 'ibkr',+ external_id: 'ibkr_cash_docs_1',+ entryable: Transaction.new(+ investment_activity_label: 'Dividend',+ extra: {+ 'exchange_rate' => 1.08,+ 'security_id' => security.id,+ 'ibkr' => { 'type' => 'Dividends' }+ }+ )+ )+ entry.transaction+ end+let!(:another_transaction) doentry = account.entries.create!(name: 'Coffee',@@ -303,7 +327,15 @@ RSpec.describe 'API V1 Transactions', type: :request doresponse '200', 'transaction retrieved' doschema '$ref' => '#/components/schemas/Transaction'- run_test!+ # The dividend, so the populated exchange_rate and amount_currency are+ # checked against the schema too.+ let(:id) { dividend_transaction.id }++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['exchange_rate']).to eq(1.08)+ expect(data['amount_currency']).to eq('EUR')+ endendresponse '404', 'transaction not found' dodiff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rbindex cd1452ea02..93df7d1f60 100644--- a/spec/swagger_helper.rb+++ b/spec/swagger_helper.rb@@ -1058,6 +1058,31 @@ RSpec.configure do |config|},excluded: { type: :boolean, description: 'Whether the transaction is excluded from budget and report totals. Splitting a transaction marks it excluded.' },split_parent: { type: :boolean, description: 'Whether the transaction has been split; its amount is then carried by its split children.' },+ investment_activity_label: {+ type: :string,+ nullable: true,+ description: 'Investment activity of a brokerage cash row, such as Dividend, Interest or Fee'+ },+ provider_type: {+ type: :string,+ nullable: true,+ description: "The importing provider's type for the row, such as IBKR's \"Withholding Tax\", when one is recorded. For CoinSpot, Sure sets it from the kind of movement."+ },+ security_id: {+ type: :string,+ format: :uuid,+ nullable: true,+ description: 'Sure security the row relates to (for example the one that paid a dividend), when the importer recorded it. GET /api/v1/securities/{id} finds it only if an account holds or has traded it.'+ },+ exchange_rate: {+ type: :number,+ nullable: true,+ description: "Rate from the transaction's currency to the account's currency stored on it. Null when none is stored or the transaction is in the account's currency."+ },+ amount_currency: {+ type: :string,+ description: 'Currency of the amount, always the same as currency on a transaction.'+ },account: { '$ref' => '#/components/schemas/Account' },category: { '$ref' => '#/components/schemas/Category', nullable: true },merchant: { '$ref' => '#/components/schemas/Merchant', nullable: true },@@ -1746,6 +1771,17 @@ RSpec.configure do |config|qty: { type: :string },price: { type: :string },investment_activity_label: { type: :string, nullable: true },+ fee: { type: :string, description: 'Fee charged on the trade, formatted like price' },+ fee_decimal: { type: :string, description: 'Fee as the exact stored, unrounded, locale-independent decimal string. A purchase fee adds to the cost and a sale fee comes off the proceeds' },+ exchange_rate: {+ type: :number,+ nullable: true,+ description: "Rate to the account's currency stored on the trade, such as one reported by the provider. The cost basis applies it to price and fee, from currency; the cash balance applies it to amount, from amount_currency. The two match unless an edit changed only the amount's currency. It was recorded for currency; when amount_currency differs, the cash balance reuses it unchanged. Null when none is stored or both currencies are the account's."+ },+ amount_currency: {+ type: :string,+ description: "Currency of the trade's amount (the entry's), which the cash balance converts from with exchange_rate. It can differ from currency, the trade's own."+ },lot_source_trade_id: { type: :string, format: :uuid, nullable: true, description: 'For a sale, the trade whose lot it names to sell from first. It applies only while the account sells by FIFO; an account that sells by average keeps it but sells from the pooled average.' },account: { '$ref' => '#/components/schemas/Account' },security: {diff --git a/test/controllers/api/v1/trades_controller_test.rb b/test/controllers/api/v1/trades_controller_test.rbindex e3c12e9b03..f60588d0cd 100644--- a/test/controllers/api/v1/trades_controller_test.rb+++ b/test/controllers/api/v1/trades_controller_test.rb@@ -1256,6 +1256,215 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTestassert trade_data.key?("notes")end+ test "show exposes the fee and the exchange rate stored on the trade" do+ security = Security.create!(ticker: "TAXF", name: "Tax Fields Security", country_code: "US")+ entry = @investment_account.entries.create!(+ date: Date.current,+ amount: 1001.25,+ name: "Buy TAXF",+ currency: "EUR",+ entryable: Trade.new(+ security: security,+ qty: 10,+ price: 100,+ fee: 1.2534,+ currency: "EUR",+ investment_activity_label: "Buy",+ extra: { "exchange_rate" => 0.9123, "provider_raw" => { "account_number" => "U1234567" } }+ )+ )++ get api_v1_trade_url(entry.entryable), headers: api_headers(read_only_api_key)+ assert_response :success++ body = JSON.parse(response.body)+ assert_equal "1.2534", body["fee_decimal"]+ assert_equal Money.new(BigDecimal("1.2534"), "EUR").format, body["fee"]+ assert_equal 0.9123, body["exchange_rate"]+ assert_not body.key?("extra")+ assert_not_includes response.body, "U1234567"+ end++ test "index returns a zero fee and a null exchange rate when the trade has none" do+ security = Security.create!(ticker: "TAXN", name: "No Rate Security", country_code: "US")+ entry = @investment_account.entries.create!(+ date: Date.current,+ amount: 500,+ name: "Buy TAXN",+ currency: "USD",+ entryable: Trade.new(security: security, qty: 5, price: 100, currency: "USD", investment_activity_label: "Buy")+ )++ get api_v1_trades_url, params: { account_id: @investment_account.id, per_page: 100 }, headers: api_headers(read_only_api_key)+ assert_response :success++ trade_json = JSON.parse(response.body)["trades"].find { |trade| trade["id"] == entry.entryable.id }+ assert trade_json+ assert_equal "0.0", trade_json["fee_decimal"]+ assert trade_json.key?("exchange_rate")+ assert_nil trade_json["exchange_rate"]+ end++ test "show and index return a null exchange rate instead of failing when extra is not a hash" do+ security = Security.create!(ticker: "TAXX", name: "Malformed Extra Security", country_code: "US")+ entry = @investment_account.entries.create!(+ date: Date.current,+ amount: 500,+ name: "Buy TAXX",+ currency: "EUR",+ entryable: Trade.new(security: security, qty: 5, price: 100, currency: "EUR", investment_activity_label: "Buy")+ )+ trade = entry.entryable++ [ [ 1, 2 ], "raw-string-extra" ].each do |malformed|+ # Written past the model, as a provider or a migration writing SQL might.+ trade.update_column(:extra, malformed)++ get api_v1_trade_url(trade), headers: api_headers(read_only_api_key)+ assert_response :success, "show failed for extra = #{malformed.inspect}"+ assert_nil JSON.parse(response.body)["exchange_rate"]++ get api_v1_trades_url, params: { account_id: @investment_account.id, per_page: 100 }, headers: api_headers(read_only_api_key)+ assert_response :success, "index failed for extra = #{malformed.inspect}"+ trade_json = JSON.parse(response.body)["trades"].find { |row| row["id"] == trade.id }+ assert trade_json+ assert_nil trade_json["exchange_rate"]+ end+ end++ test "exchange rate is read the way the app converts it and only where it applies" do+ security = Security.create!(ticker: "TAXR", name: "Rate Parsing Security", country_code: "US")+ entry = @investment_account.entries.create!(+ date: Date.current,+ amount: 500,+ name: "Buy TAXR",+ currency: "EUR",+ entryable: Trade.new(security: security, qty: 5, price: 100, currency: "EUR", investment_activity_label: "Buy")+ )+ trade = entry.entryable++ # Float() would read "0x10" as 16; the app's to_d reads it as 0 and+ # refuses to convert with it.+ trade.update_column(:extra, { "exchange_rate" => "0x10" })+ get api_v1_trade_url(trade), headers: api_headers(read_only_api_key)+ assert_response :success+ assert_nil JSON.parse(response.body)["exchange_rate"]++ trade.update_column(:extra, { "exchange_rate" => "1.0850" })+ get api_v1_trade_url(trade), headers: api_headers(read_only_api_key)+ assert_equal 1.085, JSON.parse(response.body)["exchange_rate"]++ # A trade in the account's own currency is never converted, so a stored+ # rate on it is not exposed.+ entry.update_columns(currency: @investment_account.currency)+ trade.update_columns(currency: @investment_account.currency, extra: { "exchange_rate" => 1.085 })+ get api_v1_trade_url(trade), headers: api_headers(read_only_api_key)+ assert_nil JSON.parse(response.body)["exchange_rate"]+ end++ # The cost basis converts price and fee from trade.currency with the stored+ # rate (Holding::TradeCalculatorHelpers), and the web form and+ # PATCH /api/v1/trades/:id change entry.currency without touching+ # trade.currency, so the rate stays tied to the trade's currency there. The+ # cash balance (Balance::SyncCache) converts the amount from the entry's+ # currency with the same rate.+ test "exchange rate stays tied to the trade's currency when the entry's currency changes" do+ security = Security.create!(ticker: "TAXC", name: "Currency Mismatch Security", country_code: "US")+ entry = @investment_account.entries.create!(+ date: Date.current,+ amount: 100,+ name: "Buy TAXC",+ currency: "EUR",+ entryable: Trade.new(security: security, qty: 1, price: 100, currency: "EUR", investment_activity_label: "Buy",+ extra: { "exchange_rate" => 1.1 })+ )+ trade = entry.entryable++ patch api_v1_trade_url(trade), params: { trade: { currency: "GBP" } }, headers: api_headers(read_write_api_key)+ assert_response :success+ assert_equal "GBP", entry.reload.currency+ assert_equal "EUR", trade.reload.currency+ assert_equal 110, Money.new(trade.price, trade.currency).exchange_to("USD", custom_rate: trade.exchange_rate).amount,+ "the cost basis converts from the trade's currency with the stored rate"++ get api_v1_trade_url(trade), headers: api_headers(read_only_api_key)+ assert_response :success+ body = JSON.parse(response.body)+ assert_equal 1.1, body["exchange_rate"]+ assert_equal "EUR", body["currency"]+ assert_equal "GBP", body["amount_currency"]++ get api_v1_trades_url, params: { account_id: @investment_account.id, per_page: 100 }, headers: api_headers(read_only_api_key)+ assert_response :success+ trade_json = JSON.parse(response.body)["trades"].find { |row| row["id"] == trade.id }+ assert_equal 1.1, trade_json["exchange_rate"]+ assert_equal "GBP", trade_json["amount_currency"]++ # Moving the entry into the account's currency leaves the rate the cost+ # basis still applies.+ patch api_v1_trade_url(trade), params: { trade: { currency: @investment_account.currency } }, headers: api_headers(read_write_api_key)+ assert_response :success+ get api_v1_trade_url(trade), headers: api_headers(read_only_api_key)+ assert_equal 1.1, JSON.parse(response.body)["exchange_rate"]++ # The other way round, the cost basis never applies the rate but the cash+ # balance converts the amount from the entry's currency with it.+ entry.update_columns(currency: "EUR")+ trade.update_columns(currency: @investment_account.currency)+ assert_equal 110, entry.reload.amount_money.exchange_to("USD", custom_rate: trade.reload.exchange_rate).amount,+ "the cash balance converts from the entry's currency with the stored rate"+ get api_v1_trade_url(trade), headers: api_headers(read_only_api_key)+ body = JSON.parse(response.body)+ assert_equal 1.1, body["exchange_rate"]+ assert_equal "USD", body["currency"]+ assert_equal "EUR", body["amount_currency"]++ # With both in the account's currency, neither path applies it.+ entry.update_columns(currency: @investment_account.currency)+ get api_v1_trade_url(trade), headers: api_headers(read_only_api_key)+ assert_nil JSON.parse(response.body)["exchange_rate"]+ end++ test "exchange rate compares currency codes regardless of case" do+ security = Security.create!(ticker: "TAXL", name: "Lower Case Currency Security", country_code: "US")+ entry = @investment_account.entries.create!(+ date: Date.current,+ amount: 100,+ name: "Buy TAXL",+ currency: "usd",+ entryable: Trade.new(security: security, qty: 1, price: 100, currency: "usd", investment_activity_label: "Buy",+ extra: { "exchange_rate" => 1.1 })+ )+ assert_equal 100, entry.amount_money.exchange_to("USD", custom_rate: entry.entryable.exchange_rate).amount,+ "Money treats usd as the account's currency"++ get api_v1_trade_url(entry.entryable), headers: api_headers(read_only_api_key)+ assert_response :success+ assert_nil JSON.parse(response.body)["exchange_rate"]+ end++ # A stored decimal can be positive and finite yet become 0.0 or Infinity+ # as a Float, which is what the response carries.+ test "exchange rate is null when the stored value does not fit a Float" do+ security = Security.create!(ticker: "TAXF", name: "Float Range Security", country_code: "US")+ entry = @investment_account.entries.create!(+ date: Date.current,+ amount: 100,+ name: "Buy TAXF",+ currency: "EUR",+ entryable: Trade.new(security: security, qty: 1, price: 100, currency: "EUR", investment_activity_label: "Buy")+ )+ trade = entry.entryable++ [ "1e-400", "1e400" ].each do |stored|+ trade.update_column(:extra, { "exchange_rate" => stored })+ get api_v1_trade_url(trade), headers: api_headers(read_only_api_key)+ assert_response :success+ assert_nil JSON.parse(response.body)["exchange_rate"], stored+ assert_nil trade.reload.numeric_exchange_rate, stored+ end+ end+test "a member cannot list, read, change or add trades on accounts they cannot reach" domember = users(:family_member)member.api_keys.active.destroy_alldiff --git a/test/controllers/api/v1/transactions_controller_test.rb b/test/controllers/api/v1/transactions_controller_test.rbindex 65af6ed13e..b9b8456a92 100644--- a/test/controllers/api/v1/transactions_controller_test.rb+++ b/test/controllers/api/v1/transactions_controller_test.rb@@ -1788,6 +1788,146 @@ endassert_equal false, row["excluded"]end+ test "show exposes the activity label and the safe provider fields, not the raw extra" do+ security = Security.create!(ticker: "WHT#{SecureRandom.hex(2).upcase}", name: "Withholding Security", country_code: "US")+ entry = create_transaction(+ account: @account,+ amount: 1.5,+ name: "Withholding Tax for WHT",+ currency: "EUR",+ source: "ibkr",+ external_id: "ibkr_cash_#{SecureRandom.hex(4)}",+ entryable: Transaction.new(+ investment_activity_label: "Dividend",+ extra: {+ "exchange_rate" => 0.9215,+ "security_id" => security.id,+ "ibkr" => { "type" => "Withholding Tax", "conid" => "CONID-SECRET-1", "account_id" => "U7654321" }+ }+ )+ )++ get api_v1_transaction_url(entry.entryable), headers: api_headers(@read_only_api_key)+ assert_response :success++ body = JSON.parse(response.body)+ assert_equal "Dividend", body["investment_activity_label"]+ assert_equal "Withholding Tax", body["provider_type"]+ assert_equal security.id, body["security_id"]+ assert_equal 0.9215, body["exchange_rate"]+ assert_equal "EUR", body["amount_currency"]+ assert_not body.key?("extra")+ assert_not_includes response.body, "CONID-SECRET-1"+ assert_not_includes response.body, "U7654321"+ end++ test "index returns null tax fields for a plain transaction and ignores a provider payload that is not a hash" do+ entry = create_transaction(+ account: @account,+ name: "Plain row",+ source: "plaid",+ entryable: Transaction.new+ )+ # Written past validation, as a provider writing extra directly might.+ entry.entryable.update_column(:extra, { "plaid" => "raw-string-payload", "security" => "raw-string-security", "exchange_rate" => "not-a-number" })++ get api_v1_transactions_url, params: { account_id: @account.id, per_page: 100 }, headers: api_headers(@read_only_api_key)+ assert_response :success++ txn_json = JSON.parse(response.body)["transactions"].find { |txn| txn["id"] == entry.entryable.id }+ assert txn_json+ %w[investment_activity_label provider_type security_id exchange_rate].each do |field|+ assert txn_json.key?(field), "expected #{field} in the response"+ assert_nil txn_json[field], "expected #{field} to be null"+ end+ assert_not_includes response.body, "raw-string-payload"+ assert_not_includes response.body, "raw-string-security"+ end++ test "show and index return null tax fields instead of failing when extra is not a hash" do+ entry = create_transaction(account: @account, name: "Malformed extra row", source: "ibkr", currency: "EUR", entryable: Transaction.new)+ transaction = entry.entryable++ [ [ 1, 2 ], "raw-string-extra" ].each do |malformed|+ # Written past the model, as a provider or a migration writing SQL might.+ transaction.update_column(:extra, malformed)++ get api_v1_transaction_url(transaction), headers: api_headers(@read_only_api_key)+ assert_response :success, "show failed for extra = #{malformed.inspect}"+ body = JSON.parse(response.body)++ get api_v1_transactions_url, params: { account_id: @account.id, per_page: 100 }, headers: api_headers(@read_only_api_key)+ assert_response :success, "index failed for extra = #{malformed.inspect}"+ txn_json = JSON.parse(response.body)["transactions"].find { |row| row["id"] == transaction.id }+ assert txn_json++ [ body, txn_json ].each do |json|+ %w[provider_type security_id exchange_rate].each do |field|+ assert json.key?(field), "expected #{field} in the response"+ assert_nil json[field], "expected #{field} to be null for extra = #{malformed.inspect}"+ end+ end+ end+ end++ test "security_id is only a uuid string, never other data stored under the key" do+ entry = create_transaction(account: @account, name: "Odd security id", currency: "EUR", entryable: Transaction.new)+ transaction = entry.entryable++ [ { "account_number" => "U9999999" }, 12345, "not-a-uuid", [ "U9999999" ] ].each do |stored|+ transaction.update_column(:extra, { "security_id" => stored })++ get api_v1_transaction_url(transaction), headers: api_headers(@read_only_api_key)+ assert_response :success+ assert_nil JSON.parse(response.body)["security_id"], "expected null for security_id = #{stored.inspect}"+ assert_not_includes response.body, "U9999999"+ end+ end++ # A stored decimal can be positive and finite yet become 0.0 or Infinity+ # as a Float, which is what the response carries.+ test "exchange rate is null when the stored value does not fit a Float" do+ entry = create_transaction(account: @account, name: "Float range row", currency: "EUR", entryable: Transaction.new)+ transaction = entry.entryable++ [ "1e-400", "1e400" ].each do |stored|+ transaction.update_column(:extra, { "exchange_rate" => stored })+ get api_v1_transaction_url(transaction), headers: api_headers(@read_only_api_key)+ assert_response :success+ assert_nil JSON.parse(response.body)["exchange_rate"], stored+ assert_nil transaction.reload.numeric_exchange_rate, stored+ end+ end++ test "exchange rate compares currency codes regardless of case" do+ entry = create_transaction(account: @account, name: "Lower case row", currency: "EUR", entryable: Transaction.new)+ entry.update_column(:currency, @account.currency.downcase)+ entry.entryable.update_column(:extra, { "exchange_rate" => 1.1 })++ get api_v1_transaction_url(entry.entryable), headers: api_headers(@read_only_api_key)+ assert_response :success+ assert_nil JSON.parse(response.body)["exchange_rate"]+ end++ test "exchange rate is read the way the app converts it and only where it applies" do+ entry = create_transaction(account: @account, name: "Rate row", currency: "EUR", entryable: Transaction.new)+ transaction = entry.entryable++ # Float() would read "0x10" as 16; the app's to_d reads it as 0 and+ # refuses to convert with it.+ transaction.update_column(:extra, { "exchange_rate" => "0x10" })+ get api_v1_transaction_url(transaction), headers: api_headers(@read_only_api_key)+ assert_response :success+ assert_nil JSON.parse(response.body)["exchange_rate"]++ # A row in the account's own currency is never converted, so a stored rate+ # on it is not exposed.+ entry.update_column(:currency, @account.currency)+ transaction.update_column(:extra, { "exchange_rate" => 1.085 })+ get api_v1_transaction_url(transaction), headers: api_headers(@read_only_api_key)+ assert_nil JSON.parse(response.body)["exchange_rate"]+ end+privatedef foreign_categorydiff --git a/test/models/family/data_exporter_test.rb b/test/models/family/data_exporter_test.rbindex 0ed8ce18b6..de7e5f59ed 100644--- a/test/models/family/data_exporter_test.rb+++ b/test/models/family/data_exporter_test.rb@@ -1305,6 +1305,257 @@ class Family::DataExporterTest < ActiveSupport::TestCaseendend+ test "exports trade fee, activity label and stored exchange rate in NDJSON" do+ investment_account = @family.accounts.create!(+ name: "Tax Investment Account",+ accountable: Investment.new,+ balance: 10_000,+ currency: "EUR"+ )+ security = Security.create!(ticker: "TAX#{SecureRandom.hex(3).upcase}", name: "Tax Export Security")+ entry = investment_account.entries.create!(+ date: Date.parse("2024-05-20"),+ amount: 1002.5,+ name: "Buy",+ currency: "USD",+ entryable: Trade.new(+ security: security,+ qty: 10,+ price: 100,+ fee: 2.5,+ currency: "USD",+ investment_activity_label: "Buy",+ extra: { "exchange_rate" => 0.92, "ibkr" => { "account_id" => "U1234567" } }+ )+ )++ Zip::File.open_buffer(@exporter.generate_export) do |zip|+ records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }+ trade_data = records.find { |record| record["type"] == "Trade" && record.dig("data", "id") == entry.entryable.id }["data"]++ assert_equal "2.5", BigDecimal(trade_data["fee"].to_s).to_s("F")+ assert_equal "Buy", trade_data["investment_activity_label"]+ assert_equal 0.92, trade_data["exchange_rate"]+ assert_not trade_data.key?("extra")+ assert_not_includes zip.read("all.ndjson"), "U1234567"+ end+ end++ # The cost basis applies a trade's stored rate from currency (the trade's)+ # and the cash balance from the entry's currency, which an edit can make+ # differ. The rate is exported when either path applies it, with both+ # currencies named.+ test "exports the amount's currency next to the rate on trades and transactions" do+ investment_account = @family.accounts.create!(+ name: "Amount Currency Account",+ accountable: Investment.new,+ balance: 10_000,+ currency: "USD"+ )+ security = Security.create!(ticker: "AMC#{SecureRandom.hex(3).upcase}", name: "Amount Currency Security")+ # Only the cost basis applies the rate: the entry is in the account's currency.+ cost_basis_entry = investment_account.entries.create!(+ date: Date.parse("2024-05-20"),+ amount: 100,+ name: "Buy",+ currency: "USD",+ entryable: Trade.new(security: security, qty: 1, price: 100, currency: "EUR", investment_activity_label: "Buy",+ extra: { "exchange_rate" => 1.1 })+ )+ # Only the cash balance applies it: the trade is in the account's currency.+ cash_entry = investment_account.entries.create!(+ date: Date.parse("2024-05-20"),+ amount: -5,+ name: "Dividend",+ currency: "EUR",+ entryable: Trade.new(security: security, qty: 0, price: 0, currency: "USD", investment_activity_label: "Dividend",+ extra: { "exchange_rate" => 1.2 })+ )+ transaction_entry = investment_account.entries.create!(+ date: Date.parse("2024-05-21"),+ amount: -5,+ name: "Dividend",+ currency: "EUR",+ entryable: Transaction.new(investment_activity_label: "Dividend", extra: { "exchange_rate" => 1.1 })+ )++ Zip::File.open_buffer(@exporter.generate_export) do |zip|+ records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }+ data_for = ->(type, entry) { records.find { |record| record["type"] == type && record.dig("data", "id") == entry.entryable.id }["data"] }++ cost_basis_data = data_for.call("Trade", cost_basis_entry)+ assert_equal 1.1, cost_basis_data["exchange_rate"]+ assert_equal "EUR", cost_basis_data["currency"]+ assert_equal "USD", cost_basis_data["amount_currency"]++ cash_data = data_for.call("Trade", cash_entry)+ assert_equal 1.2, cash_data["exchange_rate"]+ assert_equal "USD", cash_data["currency"]+ assert_equal "EUR", cash_data["amount_currency"]++ transaction_data = data_for.call("Transaction", transaction_entry)+ assert_equal "EUR", transaction_data["amount_currency"]+ assert_equal 1.1, transaction_data["exchange_rate"]+ end+ end++ # numeric_exchange_rate reads each split line's account, which the export+ # preloads, so more split parents do not mean more account queries.+ test "split lines do not query accounts once per line" do+ make_split = lambda do+ parent = @account.entries.create!(date: Date.parse("2024-05-23"), amount: -10, name: "Split", currency: "EUR",+ entryable: Transaction.new)+ parent.split!([ { name: "A", amount: -6 }, { name: "B", amount: -4 } ]).each do |child|+ child.entryable.update_columns(extra: { "exchange_rate" => 1.08 })+ end+ end+ count_account_queries = lambda do+ count = 0+ callback = ->(*, payload) { count += 1 if payload[:sql].match?(/FROM "accounts"/) }+ ActiveSupport::Notifications.subscribed(callback, "sql.active_record") { @exporter.generate_export }+ count+ end++ make_split.call+ baseline = count_account_queries.call+ 3.times { make_split.call }++ assert_equal baseline, count_account_queries.call+ end++ test "exports the activity label and safe provider fields on split lines" do+ security = Security.create!(ticker: "SPL#{SecureRandom.hex(3).upcase}", name: "Split Line Security")+ parent = @account.entries.create!(+ date: Date.parse("2024-05-22"),+ amount: -10,+ name: "Dividend to split",+ currency: "EUR",+ entryable: Transaction.new(investment_activity_label: "Dividend")+ )+ child = parent.split!([+ { name: "Dividend part", amount: -6 },+ { name: "Other part", amount: -4 }+ ]).first+ # Split children start without these; a provider or a later edit can+ # store them, as on any other row.+ child.update_columns(source: "ibkr")+ child.entryable.update_columns(+ investment_activity_label: "Dividend",+ extra: {+ "exchange_rate" => 1.08,+ "security_id" => security.id,+ "ibkr" => { "type" => "Dividends", "account_id" => "U5550001" }+ }+ )++ Zip::File.open_buffer(@exporter.generate_export) do |zip|+ ndjson = zip.read("all.ndjson")+ records = ndjson.split("\n").map { |line| JSON.parse(line) }+ parent_data = records.find { |record| record["type"] == "Transaction" && record.dig("data", "id") == parent.entryable.id }["data"]+ lines = parent_data["split_lines"]+ child_line = lines.find { |line| line["id"] == child.entryable.id }+ other_line = lines.find { |line| line["id"] != child.entryable.id }++ assert_equal "Dividend", child_line["investment_activity_label"]+ assert_equal "Dividends", child_line["provider_type"]+ assert_equal security.id, child_line["security_id"]+ assert_equal 1.08, child_line["exchange_rate"]+ assert_equal "EUR", child_line["amount_currency"]+ %w[investment_activity_label provider_type security_id exchange_rate].each do |field|+ assert other_line.key?(field), "expected #{field} on the split line"+ assert_nil other_line[field]+ end+ assert_not_includes ndjson, "U5550001"+ end+ end++ test "export reads a non-hash extra on a trade or transaction as null tax fields" do+ investment_account = @family.accounts.create!(+ name: "Malformed Extra Investment Account",+ accountable: Investment.new,+ balance: 10_000,+ currency: "EUR"+ )+ security = Security.create!(ticker: "TMX#{SecureRandom.hex(3).upcase}", name: "Malformed Extra Security")+ trade_entry = investment_account.entries.create!(+ date: Date.parse("2024-05-20"),+ amount: 500,+ name: "Buy",+ currency: "USD",+ entryable: Trade.new(security: security, qty: 5, price: 100, currency: "USD", investment_activity_label: "Buy")+ )+ transaction_entry = @account.entries.create!(+ date: Date.parse("2024-05-21"),+ amount: 1.5,+ name: "Malformed",+ currency: "EUR",+ source: "ibkr",+ entryable: Transaction.new+ )++ [ [ 1, 2 ], "raw-string-extra" ].each do |malformed|+ # Written past the model, as a provider or a migration writing SQL might.+ trade_entry.entryable.update_column(:extra, malformed)+ transaction_entry.entryable.update_column(:extra, malformed)++ Zip::File.open_buffer(@exporter.generate_export) do |zip|+ records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }+ trade_data = records.find { |record| record["type"] == "Trade" && record.dig("data", "id") == trade_entry.entryable.id }["data"]+ transaction_data = records.find { |record| record["type"] == "Transaction" && record.dig("data", "id") == transaction_entry.entryable.id }["data"]++ assert_nil trade_data["exchange_rate"]+ %w[provider_type security_id exchange_rate].each do |field|+ assert transaction_data.key?(field)+ assert_nil transaction_data[field], "expected #{field} to be null for extra = #{malformed.inspect}"+ end+ end+ end+ end++ test "exports transaction activity label and safe provider fields in NDJSON" do+ security = Security.create!(ticker: "WHX#{SecureRandom.hex(3).upcase}", name: "Withholding Export Security")+ entry = @account.entries.create!(+ date: Date.parse("2024-05-21"),+ amount: 1.5,+ name: "Withholding Tax",+ currency: "EUR",+ source: "ibkr",+ entryable: Transaction.new(+ investment_activity_label: "Dividend",+ extra: {+ "exchange_rate" => 0.93,+ "security_id" => security.id,+ "ibkr" => { "type" => "Withholding Tax", "conid" => "CONID-SECRET-2" }+ }+ )+ )+ plain_entry = @account.entries.create!(+ date: Date.parse("2024-05-22"),+ amount: 10,+ name: "Plain",+ currency: "USD",+ entryable: Transaction.new+ )++ Zip::File.open_buffer(@exporter.generate_export) do |zip|+ records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }+ transaction_data = records.find { |record| record["type"] == "Transaction" && record.dig("data", "id") == entry.entryable.id }["data"]+ plain_data = records.find { |record| record["type"] == "Transaction" && record.dig("data", "id") == plain_entry.entryable.id }["data"]++ assert_equal "Dividend", transaction_data["investment_activity_label"]+ assert_equal "Withholding Tax", transaction_data["provider_type"]+ assert_equal security.id, transaction_data["security_id"]+ assert_equal 0.93, transaction_data["exchange_rate"]+ assert_not transaction_data.key?("extra")+ assert_not_includes zip.read("all.ndjson"), "CONID-SECRET-2"++ %w[investment_activity_label provider_type security_id exchange_rate].each do |field|+ assert plain_data.key?(field)+ assert_nil plain_data[field]+ end+ end+ end+# CSV formula injection (CWE-1236) -------------------------------------------## These assert on the emitted CSV rather than on the helper. Sanitizing field@@ -1412,7 +1663,6 @@ class Family::DataExporterTest < ActiveSupport::TestCaseendend-privatedef create_transaction_entry(account, amount:, date:, name:)