mirror of
https://github.com/we-promise/sure.git
synced 2026-05-12 23:25:00 +00:00
* 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>
158 lines
5.4 KiB
Ruby
158 lines
5.4 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
class IndexaCapitalItem::Importer
|
|
include SyncStats::Collector
|
|
include IndexaCapitalAccount::DataHelpers
|
|
|
|
attr_reader :indexa_capital_item, :indexa_capital_provider, :sync
|
|
|
|
def initialize(indexa_capital_item, indexa_capital_provider:, sync: nil)
|
|
@indexa_capital_item = indexa_capital_item
|
|
@indexa_capital_provider = indexa_capital_provider
|
|
@sync = sync
|
|
end
|
|
|
|
class CredentialsError < StandardError; end
|
|
|
|
def import
|
|
Rails.logger.info "IndexaCapitalItem::Importer - Starting import for item #{indexa_capital_item.id}"
|
|
|
|
unless indexa_capital_provider
|
|
raise CredentialsError, "No IndexaCapital provider configured for item #{indexa_capital_item.id}"
|
|
end
|
|
|
|
# Step 1: Fetch and store all accounts
|
|
import_accounts
|
|
|
|
# Step 2: For LINKED accounts only, fetch holdings data
|
|
linked_accounts = IndexaCapitalAccount
|
|
.where(indexa_capital_item_id: indexa_capital_item.id)
|
|
.joins(:account_provider)
|
|
|
|
Rails.logger.info "IndexaCapitalItem::Importer - Found #{linked_accounts.count} linked accounts to process"
|
|
|
|
linked_accounts.each do |indexa_capital_account|
|
|
Rails.logger.info "IndexaCapitalItem::Importer - Processing linked account #{indexa_capital_account.id}"
|
|
import_holdings(indexa_capital_account)
|
|
end
|
|
|
|
# Update raw payload on the item
|
|
indexa_capital_item.upsert_indexa_capital_snapshot!(stats)
|
|
rescue Provider::IndexaCapital::AuthenticationError
|
|
indexa_capital_item.update!(status: :requires_update)
|
|
raise
|
|
end
|
|
|
|
private
|
|
|
|
def stats
|
|
@stats ||= {}
|
|
end
|
|
|
|
def persist_stats!
|
|
return unless sync&.respond_to?(:sync_stats)
|
|
merged = (sync.sync_stats || {}).merge(stats)
|
|
sync.update_columns(sync_stats: merged)
|
|
end
|
|
|
|
def import_accounts
|
|
Rails.logger.info "IndexaCapitalItem::Importer - Fetching accounts from Indexa Capital API"
|
|
|
|
accounts_data = indexa_capital_provider.list_accounts
|
|
|
|
stats["api_requests"] = stats.fetch("api_requests", 0) + 1
|
|
stats["total_accounts"] = accounts_data.size
|
|
|
|
upstream_account_ids = []
|
|
|
|
accounts_data.each do |account_data|
|
|
import_account(account_data)
|
|
upstream_account_ids << account_data[:account_number].to_s if account_data[:account_number]
|
|
rescue => e
|
|
Rails.logger.error "IndexaCapitalItem::Importer - Failed to import account: #{e.message}"
|
|
stats["accounts_skipped"] = stats.fetch("accounts_skipped", 0) + 1
|
|
register_error(e, account_data: account_data)
|
|
end
|
|
|
|
persist_stats!
|
|
|
|
# Clean up accounts that no longer exist upstream
|
|
prune_removed_accounts(upstream_account_ids)
|
|
end
|
|
|
|
def import_account(account_data)
|
|
account_number = account_data[:account_number].to_s
|
|
return if account_number.blank?
|
|
|
|
# Fetch current balance from performance endpoint
|
|
begin
|
|
balance = indexa_capital_provider.get_account_balance(account_number: account_number)
|
|
account_data[:current_balance] = balance
|
|
stats["api_requests"] = stats.fetch("api_requests", 0) + 1
|
|
rescue => e
|
|
Rails.logger.warn "IndexaCapitalItem::Importer - Failed to fetch balance for #{account_number}: #{e.message}"
|
|
end
|
|
|
|
indexa_capital_account = indexa_capital_item.indexa_capital_accounts.find_or_initialize_by(
|
|
indexa_capital_account_id: account_number
|
|
)
|
|
|
|
indexa_capital_account.upsert_from_indexa_capital!(account_data)
|
|
|
|
stats["accounts_imported"] = stats.fetch("accounts_imported", 0) + 1
|
|
end
|
|
|
|
def import_holdings(indexa_capital_account)
|
|
account_number = indexa_capital_account.indexa_capital_account_id
|
|
Rails.logger.info "IndexaCapitalItem::Importer - Fetching holdings for account #{account_number}"
|
|
|
|
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)
|
|
|
|
if holdings_array.any?
|
|
holdings_hashes = holdings_array.map { |h| sdk_object_to_hash(h) }
|
|
indexa_capital_account.upsert_holdings_snapshot!(holdings_hashes)
|
|
stats["holdings_found"] = stats.fetch("holdings_found", 0) + holdings_array.size
|
|
end
|
|
rescue => e
|
|
Rails.logger.warn "IndexaCapitalItem::Importer - Failed to fetch holdings: #{e.message}"
|
|
register_error(e, context: "holdings", account_id: indexa_capital_account.id)
|
|
end
|
|
end
|
|
|
|
# fiscal-results response may be an array or a hash containing an array
|
|
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] || []
|
|
end
|
|
|
|
def prune_removed_accounts(upstream_account_ids)
|
|
return if upstream_account_ids.empty?
|
|
|
|
removed = indexa_capital_item.indexa_capital_accounts
|
|
.where.not(indexa_capital_account_id: upstream_account_ids)
|
|
|
|
if removed.any?
|
|
Rails.logger.info "IndexaCapitalItem::Importer - Pruning #{removed.count} removed accounts"
|
|
removed.destroy_all
|
|
end
|
|
end
|
|
|
|
def register_error(error, **context)
|
|
stats["errors"] ||= []
|
|
stats["errors"] << {
|
|
message: error.message,
|
|
context: context.to_s,
|
|
timestamp: Time.current.iso8601
|
|
}
|
|
end
|
|
end
|