Implement Indexa Capital provider with real API integration (#933)

* Add Indexa Capital provider scaffold

Generate Indexa Capital provider scaffolding and align credential fields with the API authentication requirements.

* Fix PR 926 lint and schema CI failures

* Implement Indexa Capital provider with real API integration

- Rewrite all broken view templates (were meta-ERB from code generator)
- Create missing select_accounts.html.erb template
- Implement real API calls: list_accounts via /users/me, get_holdings
  via /accounts/{number}/fiscal-results, get_account_balance via
  /accounts/{number}/performance
- Add API token auth support (stored token > env token > credentials)
- Add api_token column with encryption support
- Redesign settings panel: API token prominent, credentials collapsible
- Fix account balances display using performance endpoint portfolios
- Fix accounts index empty-state guard missing indexa_capital_items
- Simplify activities fetch job (no activities API endpoint exists)
- Fix i18n interpolation (%%{ -> %{) throughout locale file

* Add tests for Indexa Capital provider integration

- IndexaCapitalItemTest: validations, credentials, scopes, sync status
- IndexaCapitalAccountTest: upsert, holdings, account provider linking
- Provider::IndexaCapitalTest: auth modes, API stubs, error handling
- IndexaCapitalItemsControllerTest: CRUD, setup, linking, authorization
- Fixtures for items (token + credentials) and accounts (mutual + pension)

52 tests, 98 assertions, 0 failures

* Address code review feedback from PR #933

- Fix zero balance bug: use `nil?` instead of `present?` so 0 is stored
- Fix has_indexa_capital_credentials? to check api_token (was ignored)
- Fix build_provider to delegate to Provided concern (was ignoring token)
- Fix IndexaCapital section outside encryption_error guard in settings
- Add account_number sanitization to prevent path traversal in API URLs
- Replace all skipped processor tests with real working tests
- Add zero-balance and path-traversal test coverage

61 tests, 107 assertions, 0 failures

* Address code review round 2: credentials validation, RuboCop, test quality

- Fix RuboCop SpaceInsideArrayLiteralBrackets in credentials check
- Chain where.not calls so all three username/document/password must be present
- Require all three credentials (||) instead of any one (&&) in validate_configuration!
- Move attr_reader to private to avoid exposing credentials publicly
- Parse dates with Date.parse in extract_balance for robustness
- Remove stale TODO and Crypto from supported_account_types
- Order build_provider query deterministically by created_at
- Replace no-op holdings assertion with meaningful assert_difference

* Address code review round 3: JSON parse safety and test precision

- Rescue JSON::ParserError on 2xx responses for clearer error messages
- Fix weak balance assertion: set balance to 0 before processing, assert
  expected value (27093.01 = sum of holdings amounts)

* Include Indexa Capital in automatic family sync

Add indexa_capital_items to Family::Syncer#child_syncables so balances
and holdings refresh on daily auto-sync and login sync, not only on
manual sync button clicks.

---------

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Juan José Mata <jjmata@jjmata.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
This commit is contained in:
David Gil
2026-02-08 18:19:37 +01:00
committed by GitHub
parent d88c2151cb
commit ba442d5f26
42 changed files with 3920 additions and 6 deletions

View File

@@ -0,0 +1,180 @@
# frozen_string_literal: true
require "test_helper"
class IndexaCapitalAccount::DataHelpersTest < ActiveSupport::TestCase
# Create a test class that includes the concern
class TestHelper
include IndexaCapitalAccount::DataHelpers
# Make private methods public for testing
public :parse_decimal, :parse_date, :resolve_security, :extract_currency, :extract_security_name
end
setup do
@helper = TestHelper.new
end
# ==========================================================================
# parse_decimal tests
# ==========================================================================
test "parse_decimal returns nil for nil input" do
assert_nil @helper.parse_decimal(nil)
end
test "parse_decimal parses string to BigDecimal" do
result = @helper.parse_decimal("123.45")
assert_instance_of BigDecimal, result
assert_equal BigDecimal("123.45"), result
end
test "parse_decimal handles integer input" do
result = @helper.parse_decimal(100)
assert_instance_of BigDecimal, result
assert_equal BigDecimal("100"), result
end
test "parse_decimal handles float input" do
result = @helper.parse_decimal(99.99)
assert_instance_of BigDecimal, result
assert_in_delta 99.99, result.to_f, 0.001
end
test "parse_decimal returns BigDecimal unchanged" do
input = BigDecimal("50.25")
result = @helper.parse_decimal(input)
assert_equal input, result
end
test "parse_decimal returns nil for invalid string" do
assert_nil @helper.parse_decimal("not a number")
end
# ==========================================================================
# parse_date tests
# ==========================================================================
test "parse_date returns nil for nil input" do
assert_nil @helper.parse_date(nil)
end
test "parse_date returns Date unchanged" do
input = Date.new(2024, 6, 15)
result = @helper.parse_date(input)
assert_equal input, result
end
test "parse_date parses ISO date string" do
result = @helper.parse_date("2024-06-15")
assert_instance_of Date, result
assert_equal Date.new(2024, 6, 15), result
end
test "parse_date parses datetime string to date" do
result = @helper.parse_date("2024-06-15T10:30:00Z")
assert_instance_of Date, result
assert_equal Date.new(2024, 6, 15), result
end
test "parse_date converts Time to Date" do
input = Time.zone.parse("2024-06-15 10:30:00")
result = @helper.parse_date(input)
assert_instance_of Date, result
assert_equal Date.new(2024, 6, 15), result
end
test "parse_date returns nil for invalid string" do
assert_nil @helper.parse_date("not a date")
end
# ==========================================================================
# extract_currency tests
# ==========================================================================
test "extract_currency returns fallback for nil currency" do
result = @helper.extract_currency({}, fallback: "USD")
assert_equal "USD", result
end
test "extract_currency extracts string currency" do
result = @helper.extract_currency({ currency: "cad" })
assert_equal "CAD", result
end
test "extract_currency extracts currency from hash with code key" do
result = @helper.extract_currency({ currency: { code: "EUR" } })
assert_equal "EUR", result
end
test "extract_currency handles indifferent access" do
result = @helper.extract_currency({ "currency" => { "code" => "GBP" } })
assert_equal "GBP", result
end
# ==========================================================================
# resolve_security tests (investment providers only)
# ==========================================================================
test "resolve_security returns nil for blank ticker" do
assert_nil @helper.resolve_security("")
assert_nil @helper.resolve_security(" ")
assert_nil @helper.resolve_security(nil)
end
test "resolve_security finds existing security" do
existing = Security.create!(ticker: "XYZTEST", name: "Test Security Inc")
result = @helper.resolve_security("xyztest")
assert_equal existing, result
end
test "resolve_security creates new security when not found" do
symbol_data = { name: "Test Company Inc" }
result = @helper.resolve_security("TEST", symbol_data)
assert_not_nil result
assert_equal "TEST", result.ticker
assert_equal "Test Company Inc", result.name
end
test "resolve_security upcases ticker" do
symbol_data = { name: "Lowercase Test" }
result = @helper.resolve_security("lower", symbol_data)
assert_equal "LOWER", result.ticker
end
test "resolve_security uses ticker as fallback name" do
# Use short ticker (<=4 chars) to avoid titleize behavior
result = @helper.resolve_security("XYZ1", {})
assert_equal "XYZ1", result.name
end
# ==========================================================================
# extract_security_name tests (investment providers only)
# ==========================================================================
test "extract_security_name uses name field" do
result = @helper.extract_security_name({ name: "Apple Inc" }, "AAPL")
assert_equal "Apple Inc", result
end
test "extract_security_name falls back to description" do
result = @helper.extract_security_name({ description: "Microsoft Corp" }, "MSFT")
assert_equal "Microsoft Corp", result
end
test "extract_security_name uses ticker as fallback" do
result = @helper.extract_security_name({}, "GOOG")
assert_equal "GOOG", result
end
test "extract_security_name ignores generic type descriptions" do
result = @helper.extract_security_name({ name: "COMMON STOCK" }, "IBM")
assert_equal "IBM", result
end
end

View File

@@ -0,0 +1,111 @@
# frozen_string_literal: true
require "test_helper"
class IndexaCapitalAccount::ProcessorTest < ActiveSupport::TestCase
setup do
@family = families(:dylan_family)
@item = indexa_capital_items(:configured_with_token)
@indexa_capital_account = indexa_capital_accounts(:mutual_fund)
@account = @family.accounts.create!(
name: "Test Investment",
balance: 10000,
currency: "EUR",
accountable: Investment.new
)
@indexa_capital_account.ensure_account_provider!(@account)
@indexa_capital_account.reload
end
# ==========================================================================
# Processor tests
# ==========================================================================
test "processor initializes with indexa_capital_account" do
processor = IndexaCapitalAccount::Processor.new(@indexa_capital_account)
assert_not_nil processor
end
test "processor skips processing when no linked account" do
unlinked = indexa_capital_accounts(:pension_plan)
processor = IndexaCapitalAccount::Processor.new(unlinked)
assert_nothing_raised { processor.process }
end
test "processor updates account balance from holdings value" do
@indexa_capital_account.update!(
current_balance: 38905.21,
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
# ==========================================================================
# HoldingsProcessor tests
# ==========================================================================
test "holdings processor creates holdings from fiscal-results payload" do
@indexa_capital_account.update!(raw_holdings_payload: [
{
"amount" => 16333.96,
"titles" => 32.26,
"price" => 506.32,
"cost_price" => 390.60,
"instrument" => {
"identifier" => "IE00BFPM9V94",
"name" => "Vanguard US 500 Stk Idx Eur -Ins Plus",
"isin_code" => "IE00BFPM9V94"
}
}
])
processor = IndexaCapitalAccount::HoldingsProcessor.new(@indexa_capital_account)
assert_difference "@account.holdings.count", 1 do
processor.process
end
holding = @account.holdings.order(created_at: :desc).first
assert_equal "IE00BFPM9V94", holding.security.ticker
assert_equal 32.26, holding.qty.to_f
end
test "holdings processor skips entries without instrument identifier" do
@indexa_capital_account.update!(raw_holdings_payload: [
{ "amount" => 100, "titles" => 1, "price" => 100, "instrument" => {} }
])
processor = IndexaCapitalAccount::HoldingsProcessor.new(@indexa_capital_account)
assert_nothing_raised { processor.process }
end
test "holdings processor handles empty payload" do
@indexa_capital_account.update!(raw_holdings_payload: [])
processor = IndexaCapitalAccount::HoldingsProcessor.new(@indexa_capital_account)
assert_nothing_raised { processor.process }
end
end

View File

@@ -0,0 +1,126 @@
# frozen_string_literal: true
require "test_helper"
class IndexaCapitalAccountTest < ActiveSupport::TestCase
setup do
@family = families(:dylan_family)
@item = indexa_capital_items(:configured_with_token)
@account = indexa_capital_accounts(:mutual_fund)
end
test "belongs to indexa_capital_item" do
assert_equal @item, @account.indexa_capital_item
end
test "validates presence of name" do
@account.name = nil
assert_not @account.valid?
end
test "validates presence of currency" do
@account.currency = nil
assert_not @account.valid?
end
test "upsert_from_indexa_capital! updates from API data" do
data = {
account_number: "NEWACCT1",
name: "New Account",
type: "mutual",
status: "active",
currency: "EUR",
current_balance: 12345.67
}
new_account = @item.indexa_capital_accounts.create!(
name: "Placeholder", currency: "EUR",
indexa_capital_account_id: "NEWACCT1"
)
new_account.upsert_from_indexa_capital!(data)
new_account.reload
assert_equal "NEWACCT1", new_account.indexa_capital_account_id
assert_equal "New Account", new_account.name
assert_equal "mutual", new_account.account_type
assert_equal "active", new_account.account_status
assert_equal 12345.67, new_account.current_balance.to_f
end
test "upsert_from_indexa_capital! without balance does not overwrite existing" do
assert_equal 38905.2136, @account.current_balance.to_f
data = {
account_number: "LPYH3MCQ",
name: "Updated Name",
type: "mutual",
status: "active",
currency: "EUR"
# No current_balance
}
@account.upsert_from_indexa_capital!(data)
@account.reload
assert_equal "Updated Name", @account.name
assert_equal 38905.2136, @account.current_balance.to_f
end
test "upsert_from_indexa_capital! stores zero balance correctly" do
data = {
account_number: "LPYH3MCQ",
name: "Zero Balance Account",
type: "mutual",
status: "active",
currency: "EUR",
current_balance: 0
}
@account.upsert_from_indexa_capital!(data)
@account.reload
assert_equal 0, @account.current_balance.to_f
end
test "upsert_holdings_snapshot! stores holdings data" do
holdings = [ { instrument: { identifier: "IE00BFPM9V94" }, titles: 32, price: 506.32, amount: 16333.96 } ]
@account.upsert_holdings_snapshot!(holdings)
@account.reload
assert_equal 1, @account.raw_holdings_payload.size
assert_not_nil @account.last_holdings_sync
end
test "upsert_holdings_snapshot! skips when empty" do
@account.update!(last_holdings_sync: 1.day.ago)
original_sync = @account.last_holdings_sync
@account.upsert_holdings_snapshot!([])
@account.reload
assert_equal original_sync, @account.last_holdings_sync
end
test "ensure_account_provider! creates link" do
linked_account = Account.create!(
family: @family, name: "My Fund", balance: 1000, currency: "EUR",
accountable: Investment.new
)
assert_nil @account.account_provider
@account.ensure_account_provider!(linked_account)
assert_not_nil @account.account_provider
assert_equal linked_account, @account.account
end
test "ensure_account_provider! is idempotent" do
linked_account = Account.create!(
family: @family, name: "My Fund", balance: 1000, currency: "EUR",
accountable: Investment.new
)
@account.ensure_account_provider!(linked_account)
assert_no_difference "AccountProvider.count" do
@account.ensure_account_provider!(linked_account)
end
end
end

View File

@@ -0,0 +1,143 @@
# frozen_string_literal: true
require "test_helper"
class IndexaCapitalItemTest < ActiveSupport::TestCase
setup do
@family = families(:dylan_family)
@item = indexa_capital_items(:configured_with_token)
end
test "belongs to family" do
assert_equal @family, @item.family
end
test "has many indexa_capital_accounts" do
assert_includes @item.indexa_capital_accounts, indexa_capital_accounts(:mutual_fund)
end
test "has good status by default" do
assert_equal "good", @item.status
end
test "validates presence of name" do
item = IndexaCapitalItem.new(family: @family, api_token: "test")
assert_not item.valid?
assert_includes item.errors[:name], "can't be blank"
end
test "valid with api_token only" do
item = IndexaCapitalItem.new(family: @family, name: "Test", api_token: "test_token")
assert item.valid?
end
test "valid with username/document/password credentials" do
item = IndexaCapitalItem.new(
family: @family, name: "Test",
username: "user@example.com", document: "12345678A", password: "secret"
)
assert item.valid?
end
test "invalid without any credentials on create" do
item = IndexaCapitalItem.new(family: @family, name: "Test")
assert_not item.valid?
assert item.errors[:base].any?
end
test "credentials_configured? returns true with api_token" do
assert @item.credentials_configured?
end
test "credentials_configured? returns true with username/document/password" do
item = indexa_capital_items(:configured_with_credentials)
assert item.credentials_configured?
end
test "credentials_configured? returns false when nothing set" do
item = IndexaCapitalItem.new(family: @family, name: "Test")
refute item.credentials_configured?
end
test "indexa_capital_provider returns nil when not configured" do
item = IndexaCapitalItem.new(family: @family, name: "Test")
assert_nil item.indexa_capital_provider
end
test "indexa_capital_provider returns provider with token auth" do
provider = @item.indexa_capital_provider
assert_instance_of Provider::IndexaCapital, provider
end
test "indexa_capital_provider returns provider with credentials auth" do
item = indexa_capital_items(:configured_with_credentials)
provider = item.indexa_capital_provider
assert_instance_of Provider::IndexaCapital, provider
end
test "can be marked for deletion" do
refute @item.scheduled_for_deletion?
@item.destroy_later
assert @item.scheduled_for_deletion?
end
test "is syncable" do
assert_respond_to @item, :sync_later
assert_respond_to @item, :syncing?
end
test "scopes work correctly" do
item_for_deletion = IndexaCapitalItem.create!(
family: @family, name: "Delete Me", api_token: "test",
scheduled_for_deletion: true, created_at: 1.day.ago
)
active_items = @family.indexa_capital_items.active
assert_includes active_items, @item
refute_includes active_items, item_for_deletion
end
test "linked_accounts_count returns count of accounts with providers" do
assert_equal 0, @item.linked_accounts_count
account = Account.create!(
family: @family, name: "Linked Fund", balance: 1000, currency: "EUR",
accountable: Investment.new
)
AccountProvider.create!(account: account, provider: indexa_capital_accounts(:mutual_fund))
assert_equal 1, @item.linked_accounts_count
end
test "unlinked_accounts_count returns count of accounts without providers" do
assert_equal 2, @item.unlinked_accounts_count
end
test "sync_status_summary with no accounts" do
item = IndexaCapitalItem.create!(family: @family, name: "Empty", api_token: "test")
assert_equal I18n.t("indexa_capital_items.sync_status.no_accounts"), item.sync_status_summary
end
test "sync_status_summary with all linked" do
# Link both accounts
[ indexa_capital_accounts(:mutual_fund), indexa_capital_accounts(:pension_plan) ].each do |ica|
account = Account.create!(
family: @family, name: ica.name, balance: 1000, currency: "EUR",
accountable: Investment.new
)
AccountProvider.create!(account: account, provider: ica)
end
assert_equal I18n.t("indexa_capital_items.sync_status.synced", count: 2), @item.sync_status_summary
end
test "sync_status_summary with partial setup" do
account = Account.create!(
family: @family, name: "Fund", balance: 1000, currency: "EUR",
accountable: Investment.new
)
AccountProvider.create!(account: account, provider: indexa_capital_accounts(:mutual_fund))
assert_equal I18n.t("indexa_capital_items.sync_status.synced_with_setup", linked: 1, unlinked: 1), @item.sync_status_summary
end
end

View File

@@ -0,0 +1,156 @@
# frozen_string_literal: true
require "test_helper"
class Provider::IndexaCapitalTest < ActiveSupport::TestCase
test "initializes with api_token" do
provider = Provider::IndexaCapital.new(api_token: "test_token")
assert_instance_of Provider::IndexaCapital, provider
end
test "initializes with username/document/password" do
provider = Provider::IndexaCapital.new(
username: "user@example.com",
document: "12345678A",
password: "secret"
)
assert_instance_of Provider::IndexaCapital, provider
end
test "raises ConfigurationError without credentials" do
assert_raises Provider::IndexaCapital::ConfigurationError do
Provider::IndexaCapital.new
end
end
test "raises ConfigurationError with partial credentials" do
assert_raises Provider::IndexaCapital::ConfigurationError do
Provider::IndexaCapital.new(username: "user@example.com")
end
assert_raises Provider::IndexaCapital::ConfigurationError do
Provider::IndexaCapital.new(username: "user@example.com", document: "12345678A")
end
end
test "list_accounts calls API and returns accounts" do
provider = Provider::IndexaCapital.new(api_token: "test_token")
stub_response = OpenStruct.new(
code: 200,
body: {
accounts: [
{ account_number: "ABC12345", type: "mutual", status: "active" },
{ account_number: "DEF67890", type: "pension", status: "active" }
]
}.to_json
)
Provider::IndexaCapital.stubs(:get).returns(stub_response)
accounts = provider.list_accounts
assert_equal 2, accounts.size
assert_equal "ABC12345", accounts[0][:account_number]
assert_equal "Indexa Capital Mutual Fund (ABC12345)", accounts[0][:name]
assert_equal "EUR", accounts[0][:currency]
assert_equal "DEF67890", accounts[1][:account_number]
assert_equal "Indexa Capital Pension Plan (DEF67890)", accounts[1][:name]
end
test "get_holdings calls fiscal-results endpoint" do
provider = Provider::IndexaCapital.new(api_token: "test_token")
stub_response = OpenStruct.new(
code: 200,
body: {
fiscal_results: [
{ amount: 1814.77, titles: 9.14, price: 175.34, instrument: { identifier: "IE00BFPM9P35" } }
],
total_fiscal_results: []
}.to_json
)
Provider::IndexaCapital.stubs(:get).returns(stub_response)
data = provider.get_holdings(account_number: "ABC12345")
assert data[:fiscal_results].is_a?(Array)
assert_equal 1, data[:fiscal_results].size
end
test "get_account_balance extracts total_amount from portfolios" do
provider = Provider::IndexaCapital.new(api_token: "test_token")
stub_response = OpenStruct.new(
code: 200,
body: {
portfolios: [
{ date: "2026-02-05", total_amount: 38000.0 },
{ date: "2026-02-06", total_amount: 38905.21 }
]
}.to_json
)
Provider::IndexaCapital.stubs(:get).returns(stub_response)
balance = provider.get_account_balance(account_number: "ABC12345")
assert_equal 38905.21.to_d, balance
end
test "get_account_balance returns 0 when no portfolios" do
provider = Provider::IndexaCapital.new(api_token: "test_token")
stub_response = OpenStruct.new(
code: 200,
body: { portfolios: [] }.to_json
)
Provider::IndexaCapital.stubs(:get).returns(stub_response)
balance = provider.get_account_balance(account_number: "ABC12345")
assert_equal 0, balance
end
test "get_activities returns empty array" do
provider = Provider::IndexaCapital.new(api_token: "test_token")
result = provider.get_activities(account_number: "ABC12345")
assert_equal [], result
end
test "raises AuthenticationError on 401" do
provider = Provider::IndexaCapital.new(api_token: "bad_token")
stub_response = OpenStruct.new(code: 401, body: "Unauthorized")
Provider::IndexaCapital.stubs(:get).returns(stub_response)
assert_raises Provider::IndexaCapital::AuthenticationError do
provider.list_accounts
end
end
test "rejects invalid account_number with path traversal" do
provider = Provider::IndexaCapital.new(api_token: "test_token")
assert_raises Provider::IndexaCapital::Error do
provider.get_holdings(account_number: "../admin")
end
end
test "rejects blank account_number" do
provider = Provider::IndexaCapital.new(api_token: "test_token")
assert_raises Provider::IndexaCapital::Error do
provider.get_holdings(account_number: "")
end
end
test "raises Error on server error" do
provider = Provider::IndexaCapital.new(api_token: "test_token")
stub_response = OpenStruct.new(code: 500, body: "Internal Server Error")
Provider::IndexaCapital.stubs(:get).returns(stub_response)
assert_raises Provider::IndexaCapital::Error do
provider.list_accounts
end
end
end