Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Fix IndexaCapital sync, account setup, and balance/type bugs (#1562)

GermanDZc5503320afe4
diff --git a/app/controllers/indexa_capital_items_controller.rb b/app/controllers/indexa_capital_items_controller.rb
index 4b37eea8a3..d5872528b5 100644
--- a/app/controllers/indexa_capital_items_controller.rb
+++ b/app/controllers/indexa_capital_items_controller.rb
@@ -222,9 +222,10 @@ class IndexaCapitalItemsController < ApplicationController
end
def complete_account_setup
- account_configs = params[:accounts] || {}
+ account_ids = Array(params[:account_ids]).reject(&:blank?)
+ sync_start_dates = params[:sync_start_dates] || {}
- if account_configs.empty?
+ if account_ids.empty?
redirect_to setup_accounts_indexa_capital_item_path(@indexa_capital_item), alert: t(".no_accounts")
return
end
@@ -232,25 +233,31 @@ class IndexaCapitalItemsController < ApplicationController
created_count = 0
skipped_count = 0
- account_configs.each do |indexa_capital_account_id, config|
- next if config[:account_type] == "skip"
-
+ account_ids.each do |indexa_capital_account_id|
indexa_capital_account = @indexa_capital_item.indexa_capital_accounts.find_by(id: indexa_capital_account_id)
next unless indexa_capital_account
next if indexa_capital_account.account_provider.present?
- accountable_type = infer_accountable_type(config[:account_type], config[:subtype])
- account = create_account_from_indexa_capital(indexa_capital_account, accountable_type, config)
-
- if account&.persisted?
+ # Parse the form-supplied date up front so a malformed value is silently
+ # dropped rather than aborting the loop body after the account is
+ # already persisted (which would mark a successfully-created account
+ # as "skipped").
+ raw_sync_start_date = sync_start_dates[indexa_capital_account_id]
+ sync_start_date = (Date.parse(raw_sync_start_date.to_s) rescue nil) if raw_sync_start_date.present?
+
+ # Wrap creation, provider link, and sync_start_date persistence in a
+ # single transaction so a failure in ensure_account_provider! (or the
+ # sync_start_date update) rolls back the Account row instead of leaving
+ # an orphan that is also wrongly counted as "created".
+ ActiveRecord::Base.transaction do
+ account = create_account_from_indexa_capital(indexa_capital_account, "Investment", {})
indexa_capital_account.ensure_account_provider!(account)
- indexa_capital_account.update!(sync_start_date: config[:sync_start_date]) if config[:sync_start_date].present?
- created_count += 1
- else
- skipped_count += 1
+ indexa_capital_account.update!(sync_start_date: sync_start_date) if sync_start_date
end
+
+ created_count += 1
rescue => e
- Rails.logger.error "IndexaCapitalItemsController#complete_account_setup - Error: #{e.message}"
+ Rails.logger.error "IndexaCapitalItemsController#complete_account_setup - Error linking #{indexa_capital_account_id}: #{e.message}"
skipped_count += 1
end
diff --git a/app/models/indexa_capital_account/data_helpers.rb b/app/models/indexa_capital_account/data_helpers.rb
index b7a86b8cdf..db92837888 100644
--- a/app/models/indexa_capital_account/data_helpers.rb
+++ b/app/models/indexa_capital_account/data_helpers.rb
@@ -39,6 +39,25 @@ module IndexaCapitalAccount::DataHelpers
nil
end
+ # Extract the canonical security key from an Indexa fiscal-results row.
+ # Indexa's response shape varies between endpoints (and across time), so
+ # try the nested instrument hash first, then a few flat fallbacks. Both
+ # HoldingsProcessor and Processor#calculate_holdings_value go through
+ # this helper so they can't disagree on which rows refer to the same
+ # security.
+ def extract_instrument_key(data)
+ return nil unless data.respond_to?(:[])
+
+ hash = data.respond_to?(:with_indifferent_access) ? data.with_indifferent_access : data
+ instrument = hash[:instrument]
+ if instrument.is_a?(Hash)
+ nested = instrument.with_indifferent_access
+ return nested[:identifier] || nested[:isin_code] || nested[:isin]
+ end
+
+ hash[:identifier] || hash[:isin_code] || hash[:isin] || hash[:symbol] || hash[:ticker]
+ end
+
def parse_date(date_value)
return nil if date_value.nil?
diff --git a/app/models/indexa_capital_account/holdings_processor.rb b/app/models/indexa_capital_account/holdings_processor.rb
index f39f8677bd..7a63fcea2f 100644
--- a/app/models/indexa_capital_account/holdings_processor.rb
+++ b/app/models/indexa_capital_account/holdings_processor.rb
@@ -13,11 +13,26 @@ class IndexaCapitalAccount::HoldingsProcessor
holdings_data = @indexa_capital_account.raw_holdings_payload
return if holdings_data.blank?
- Rails.logger.info "IndexaCapitalAccount::HoldingsProcessor - Processing #{holdings_data.size} holdings"
+ # The importer normalises to total_fiscal_results (one aggregated row
+ # per security). Defensively dedupe in case a future variant feeds the
+ # per-tax-lot fiscal_results array through here — same key extraction
+ # as Processor#calculate_holdings_value via the shared DataHelpers
+ # method, so the two can't disagree on which rows refer to the same
+ # security.
+ per_security = {}
+ holdings_data.each do |holding_data|
+ data = holding_data.respond_to?(:with_indifferent_access) ? holding_data.with_indifferent_access : holding_data
+ key = extract_instrument_key(data)
+ next if key.blank?
+
+ per_security[key] = data
+ end
+
+ Rails.logger.info "IndexaCapitalAccount::HoldingsProcessor - Processing #{per_security.size} holdings (from #{holdings_data.size} input rows)"
- holdings_data.each_with_index do |holding_data, idx|
- Rails.logger.info "IndexaCapitalAccount::HoldingsProcessor - Processing holding #{idx + 1}/#{holdings_data.size}"
- process_holding(holding_data.with_indifferent_access)
+ per_security.each_value.with_index do |data, idx|
+ Rails.logger.info "IndexaCapitalAccount::HoldingsProcessor - Processing holding #{idx + 1}/#{per_security.size}"
+ process_holding(data)
rescue => e
Rails.logger.error "IndexaCapitalAccount::HoldingsProcessor - Failed to process holding #{idx + 1}: #{e.class} - #{e.message}"
Rails.logger.error e.backtrace.first(5).join("\n") if e.backtrace
@@ -45,7 +60,7 @@ class IndexaCapitalAccount::HoldingsProcessor
# profit_loss → unrealized P&L
# subscription_date → purchase date
def process_holding(data)
- ticker = extract_ticker(data)
+ ticker = extract_instrument_key(data)
return if ticker.blank?
Rails.logger.info "IndexaCapitalAccount::HoldingsProcessor - Processing holding for ticker: #{ticker}"
@@ -80,19 +95,6 @@ class IndexaCapitalAccount::HoldingsProcessor
update_holding_cost_basis(security, cost_price) if cost_price.present?
end
- # Extract ISIN from instrument data as ticker
- def extract_ticker(data)
- # Indexa Capital uses ISIN codes nested under instrument
- instrument = data[:instrument]
- if instrument.is_a?(Hash)
- instrument = instrument.with_indifferent_access
- return instrument[:identifier] || instrument[:isin]
- end
-
- # Fallback to flat fields
- data[:isin] || data[:identifier] || data[:symbol] || data[:ticker]
- end
-
# Override security name extraction for Indexa Capital
def extract_security_name(symbol_data, fallback_ticker)
symbol_data = symbol_data.with_indifferent_access if symbol_data.respond_to?(:with_indifferent_access)
diff --git a/app/models/indexa_capital_account/processor.rb b/app/models/indexa_capital_account/processor.rb
index b128f05575..8a5d951864 100644
--- a/app/models/indexa_capital_account/processor.rb
+++ b/app/models/indexa_capital_account/processor.rb
@@ -70,47 +70,55 @@ class IndexaCapitalAccount::Processor
end
def calculate_total_balance
- # Calculate total from holdings + cash for accuracy
- holdings_value = calculate_holdings_value
- cash_value = indexa_capital_account.cash_balance || 0
-
- calculated_total = holdings_value + cash_value
-
- # Use calculated total if we have holdings, otherwise trust API value
- if holdings_value > 0
- Rails.logger.info "IndexaCapitalAccount::Processor - Using calculated total: holdings=#{holdings_value} + cash=#{cash_value} = #{calculated_total}"
- calculated_total
- elsif indexa_capital_account.current_balance.present?
+ # Trust the API's reported balance when available — Indexa's holdings payload
+ # contains time-series snapshots (one row per security per date), so summing
+ # the raw entries double-counts. Fall back to a per-security latest-snapshot
+ # sum + cash only when the API total is missing.
+ if indexa_capital_account.current_balance.present?
Rails.logger.info "IndexaCapitalAccount::Processor - Using API total: #{indexa_capital_account.current_balance}"
- indexa_capital_account.current_balance
- else
- calculated_total
+ return indexa_capital_account.current_balance
end
- end
- def calculate_cash_balance
- # Use provider's cash_balance directly
- # Note: Can be negative for margin accounts
- cash = indexa_capital_account.cash_balance
- Rails.logger.info "IndexaCapitalAccount::Processor - Cash balance from API: #{cash.inspect}"
- cash || BigDecimal("0")
+ holdings_value = calculate_holdings_value
+ cash_value = indexa_capital_account.cash_balance || 0
+ calculated_total = holdings_value + cash_value
+ Rails.logger.info "IndexaCapitalAccount::Processor - Using calculated total (API balance missing): holdings=#{holdings_value} + cash=#{cash_value} = #{calculated_total}"
+ calculated_total
end
def calculate_holdings_value
holdings_data = indexa_capital_account.raw_holdings_payload || []
return 0 if holdings_data.empty?
- holdings_data.sum do |holding|
- data = holding.is_a?(Hash) ? holding.with_indifferent_access : {}
- # Indexa Capital: amount = total market value, or titles * price
+ # The importer normalises to total_fiscal_results (one aggregated row
+ # per security) so a plain sum is correct. We still defensively dedupe
+ # by instrument key in case a future provider variant feeds the
+ # per-tax-lot fiscal_results array through here — the last value wins,
+ # consistent with how HoldingsProcessor upserts holdings.
+ per_security = {}
+ holdings_data.each do |holding|
+ instrument = extract_instrument_key(holding)
+ next if instrument.blank?
+
+ data = holding.respond_to?(:with_indifferent_access) ? holding.with_indifferent_access : holding
amount = parse_decimal(data[:amount])
- if amount
- amount
- else
+ unless amount
titles = parse_decimal(data[:titles] || data[:quantity] || data[:units]) || 0
price = parse_decimal(data[:price]) || 0
- titles * price
+ amount = titles * price
end
+
+ per_security[instrument] = amount || 0
end
+
+ per_security.values.sum
+ end
+
+ def calculate_cash_balance
+ # Use provider's cash_balance directly
+ # Note: Can be negative for margin accounts
+ cash = indexa_capital_account.cash_balance
+ Rails.logger.info "IndexaCapitalAccount::Processor - Cash balance from API: #{cash.inspect}"
+ cash || BigDecimal("0")
end
end
diff --git a/app/models/indexa_capital_item/importer.rb b/app/models/indexa_capital_item/importer.rb
index 0980919b8b..2b2368710b 100644
--- a/app/models/indexa_capital_item/importer.rb
+++ b/app/models/indexa_capital_item/importer.rb
@@ -108,12 +108,20 @@ class IndexaCapitalItem::Importer
begin
holdings_data = indexa_capital_provider.get_holdings(account_number: account_number)
-
stats["api_requests"] = stats.fetch("api_requests", 0) + 1
- # The API returns fiscal-results which may be a hash with an array inside
holdings_array = normalize_holdings_response(holdings_data)
+ # Pension plans return empty fiscal-results. Fall back to the portfolio
+ # endpoint, which exposes positions for both mutual fund and pension
+ # accounts in a uniform shape we can adapt to the same structure.
+ if holdings_array.empty?
+ Rails.logger.info "IndexaCapitalItem::Importer - fiscal-results empty for #{account_number}, falling back to /portfolio"
+ portfolio_data = indexa_capital_provider.get_portfolio(account_number: account_number)
+ stats["api_requests"] = stats.fetch("api_requests", 0) + 1
+ holdings_array = positions_from_portfolio(portfolio_data)
+ end
+
if holdings_array.any?
holdings_hashes = holdings_array.map { |h| sdk_object_to_hash(h) }
indexa_capital_account.upsert_holdings_snapshot!(holdings_hashes)
@@ -125,13 +133,40 @@ class IndexaCapitalItem::Importer
end
end
- # fiscal-results response may be an array or a hash containing an array
+ # Adapt /accounts/{id}/portfolio positions into the shape that
+ # HoldingsProcessor expects (i.e. the same field set as a
+ # total_fiscal_results row). Adds a derived cost_price (per-share cost)
+ # since portfolio rows only carry cost_amount.
+ def positions_from_portfolio(portfolio_data)
+ data = portfolio_data.is_a?(Hash) ? portfolio_data.with_indifferent_access : {}
+ Array(data[:instrument_accounts]).flat_map do |account|
+ Array(account.is_a?(Hash) ? account.with_indifferent_access[:positions] : nil).map do |pos|
+ row = (pos.is_a?(Hash) ? pos.with_indifferent_access : {}).dup
+ titles = row[:titles].to_d if row[:titles]
+ cost_amount = row[:cost_amount].to_d if row[:cost_amount]
+ if row[:cost_price].blank? && titles && titles.nonzero? && cost_amount
+ row[:cost_price] = (cost_amount / titles).to_s
+ end
+ row
+ end
+ end
+ end
+
+ # fiscal-results response may be an array or a hash containing an array.
+ # Prefer total_fiscal_results: it contains one aggregated row per security
+ # with current titles/amount/cost. fiscal_results is per tax lot and also
+ # includes historical rebalance events (e.g. virtual sells/buys that
+ # generated tax events), so summing/iterating it over-counts the position.
def normalize_holdings_response(data)
return data if data.is_a?(Array)
return [] if data.nil?
- # Try common response shapes
- data[:fiscal_results] || data[:results] || data[:positions] || data[:data] || []
+ data[:total_fiscal_results].presence ||
+ data[:fiscal_results] ||
+ data[:results] ||
+ data[:positions] ||
+ data[:data] ||
+ []
end
def prune_removed_accounts(upstream_account_ids)
diff --git a/app/models/indexa_capital_item/sync_complete_event.rb b/app/models/indexa_capital_item/sync_complete_event.rb
new file mode 100644
index 0000000000..1033151320
--- /dev/null
+++ b/app/models/indexa_capital_item/sync_complete_event.rb
@@ -0,0 +1,22 @@
+class IndexaCapitalItem::SyncCompleteEvent
+ attr_reader :indexa_capital_item
+
+ def initialize(indexa_capital_item)
+ @indexa_capital_item = indexa_capital_item
+ end
+
+ def broadcast
+ indexa_capital_item.accounts.each do |account|
+ account.broadcast_sync_complete
+ end
+
+ indexa_capital_item.broadcast_replace_to(
+ indexa_capital_item.family,
+ target: "indexa_capital_item_#{indexa_capital_item.id}",
+ partial: "indexa_capital_items/indexa_capital_item",
+ locals: { indexa_capital_item: indexa_capital_item }
+ )
+
+ indexa_capital_item.family.broadcast_sync_complete
+ end
+end
diff --git a/app/models/provider/indexa_capital.rb b/app/models/provider/indexa_capital.rb
index ad7fc6ca61..52174def60 100644
--- a/app/models/provider/indexa_capital.rb
+++ b/app/models/provider/indexa_capital.rb
@@ -55,6 +55,21 @@ class Provider::IndexaCapital
end
end
+ # GET /accounts/{account_number}/portfolio → current snapshot with positions.
+ # Used as a fallback when fiscal-results is empty (e.g. pension plans, where
+ # Indexa returns {fiscal_results: [], total_fiscal_results: []} but exposes
+ # the same positions through this endpoint).
+ def get_portfolio(account_number:)
+ sanitize_account_number!(account_number)
+ with_retries("get_portfolio") do
+ response = self.class.get(
+ "#{base_url}/accounts/#{account_number}/portfolio",
+ headers: auth_headers
+ )
+ handle_response(response)
+ end
+ end
+
# GET /accounts/{account_number}/performance → latest portfolio total_amount
def get_account_balance(account_number:)
sanitize_account_number!(account_number)
diff --git a/test/controllers/indexa_capital_items_controller_test.rb b/test/controllers/indexa_capital_items_controller_test.rb
index 1f0df601bd..f382bb275c 100644
--- a/test/controllers/indexa_capital_items_controller_test.rb
+++ b/test/controllers/indexa_capital_items_controller_test.rb
@@ -56,9 +56,7 @@ class IndexaCapitalItemsControllerTest < ActionDispatch::IntegrationTest
assert_difference "Account.count", 1 do
post complete_account_setup_indexa_capital_item_url(@item), params: {
- accounts: {
- ica.id => { account_type: "investment", subtype: "brokerage" }
- }
+ account_ids: [ ica.id ]
}
end
@@ -80,21 +78,15 @@ class IndexaCapitalItemsControllerTest < ActionDispatch::IntegrationTest
assert_no_difference "Account.count" do
post complete_account_setup_indexa_capital_item_url(@item), params: {
- accounts: {
- ica.id => { account_type: "investment" }
- }
+ account_ids: [ ica.id ]
}
end
end
- test "complete_account_setup with all skipped redirects to setup" do
- ica = indexa_capital_accounts(:mutual_fund)
-
+ test "complete_account_setup with no selected accounts redirects to setup" do
assert_no_difference "Account.count" do
post complete_account_setup_indexa_capital_item_url(@item), params: {
- accounts: {
- ica.id => { account_type: "skip" }
- }
+ account_ids: []
}
end
diff --git a/test/models/indexa_capital_account/processor_test.rb b/test/models/indexa_capital_account/processor_test.rb
index f22678cf31..d18558b7c6 100644
--- a/test/models/indexa_capital_account/processor_test.rb
+++ b/test/models/indexa_capital_account/processor_test.rb
@@ -35,7 +35,7 @@ class IndexaCapitalAccount::ProcessorTest < ActiveSupport::TestCase
assert_nothing_raised { processor.process }
end
- test "processor updates account balance from holdings value" do
+ test "processor trusts API current_balance over holdings sum when present" do
@indexa_capital_account.update!(
current_balance: 38905.21,
raw_holdings_payload: [
@@ -59,6 +59,34 @@ class IndexaCapitalAccount::ProcessorTest < ActiveSupport::TestCase
processor = IndexaCapitalAccount::Processor.new(@indexa_capital_account)
processor.process
+ @account.reload
+ assert_in_delta 38905.21, @account.balance.to_f, 0.01
+ end
+
+ test "processor falls back to holdings sum when current_balance is missing" do
+ @indexa_capital_account.update!(
+ current_balance: nil,
+ raw_holdings_payload: [
+ {
+ "amount" => 16333.96,
+ "titles" => 32.26,
+ "price" => 506.32,
+ "instrument" => { "identifier" => "IE00BFPM9V94", "name" => "Vanguard US 500" }
+ },
+ {
+ "amount" => 10759.05,
+ "titles" => 40.34,
+ "price" => 266.71,
+ "instrument" => { "identifier" => "IE00BFPM9L96", "name" => "Vanguard European" }
+ }
+ ]
+ )
+
+ @account.update!(balance: 0)
+
+ processor = IndexaCapitalAccount::Processor.new(@indexa_capital_account)
+ processor.process
+
@account.reload
assert_in_delta 27093.01, @account.balance.to_f, 0.01
end