Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Let users ignore Indexa Capital and Enable Banking accounts they don't want synced (#5119)

David Gil651b7fe7512e
diff --git a/app/controllers/enable_banking_items_controller.rb b/app/controllers/enable_banking_items_controller.rb
index 639a667470..e97675f32e 100644
--- a/app/controllers/enable_banking_items_controller.rb
+++ b/app/controllers/enable_banking_items_controller.rb
@@ -308,9 +308,7 @@ class EnableBankingItemsController < ApplicationController
# Show setup accounts modal
def setup_accounts
- @enable_banking_accounts = @enable_banking_item.enable_banking_accounts
- .left_joins(:account_provider)
- .where(account_providers: { id: nil })
+ @enable_banking_accounts = @enable_banking_item.enable_banking_accounts.needs_setup
@account_type_options = [
[ "Skip this account", "skip" ],
@@ -364,13 +362,15 @@ class EnableBankingItemsController < ApplicationController
skipped_count = 0
account_types.each do |enable_banking_account_id, selected_type|
- # Skip accounts marked as "skip"
+ enable_banking_account = @enable_banking_item.enable_banking_accounts.find(enable_banking_account_id)
+
if selected_type == "skip" || selected_type.blank?
+ # Persist the skip so the account stops resurfacing as "needs setup" and the
+ # importer stops fetching it.
+ enable_banking_account.ignore!
skipped_count += 1
next
end
-
- enable_banking_account = @enable_banking_item.enable_banking_accounts.find(enable_banking_account_id)
selected_subtype = account_subtypes[enable_banking_account_id]
# Default subtype for CreditCard since it only has one option
@@ -401,7 +401,7 @@ class EnableBankingItemsController < ApplicationController
if created_count > 0
flash[:notice] = t(".success", default: "%{count} account(s) created successfully!", count: created_count)
elsif skipped_count > 0
- flash[:notice] = t(".all_skipped", default: "All accounts were skipped. You can set them up later from the accounts page.")
+ flash[:notice] = t(".all_skipped")
else
flash[:notice] = t(".no_accounts", default: "No accounts to set up.")
end
diff --git a/app/controllers/fio_items_controller.rb b/app/controllers/fio_items_controller.rb
index 69f6b39e34..0afff29a5c 100644
--- a/app/controllers/fio_items_controller.rb
+++ b/app/controllers/fio_items_controller.rb
@@ -335,9 +335,6 @@ class FioItemsController < ApplicationController
# Create and sync a Sure account from the Fio account's statement header.
def create_account_from_fio(fio_account, account_type)
- # Linking clears any prior skip so a future unlink re-prompts for setup.
- fio_account.update!(ignored: false) if fio_account.ignored?
-
# Same normalization FioAccount::Processor applies: Fio reports a drawn loan or
# overdraft negative, Sure holds a liability positive. Without it the new account
# shows a negative debt until a sync corrects it, and the next sync may well be
diff --git a/app/controllers/indexa_capital_items_controller.rb b/app/controllers/indexa_capital_items_controller.rb
index 58a3310b3c..ee0f168609 100644
--- a/app/controllers/indexa_capital_items_controller.rb
+++ b/app/controllers/indexa_capital_items_controller.rb
@@ -179,13 +179,22 @@ class IndexaCapitalItemsController < ApplicationController
account_ids = Array(params[:account_ids]).reject(&:blank?)
sync_start_dates = params[:sync_start_dates] || {}
+ # Accounts the form showed but the user left unchecked are skipped for good, so
+ # they stop resurfacing as "needs setup" and the importer stops fetching them.
+ skipped_ids = Array(params[:setup_account_ids]).reject(&:blank?) - account_ids
+ skipped_count = @indexa_capital_item.unlinked_indexa_capital_accounts.where(id: skipped_ids).to_a.count(&:ignore!)
+ @indexa_capital_item.update!(pending_account_setup: @indexa_capital_item.unlinked_accounts_count.positive?) if skipped_count > 0
+
if account_ids.empty?
- redirect_to setup_accounts_indexa_capital_item_path(@indexa_capital_item), alert: t(".no_accounts")
+ if skipped_count > 0
+ redirect_to accounts_path, notice: t(".all_skipped")
+ else
+ redirect_to setup_accounts_indexa_capital_item_path(@indexa_capital_item), alert: t(".no_accounts")
+ end
return
end
created_count = 0
- skipped_count = 0
account_ids.each do |indexa_capital_account_id|
indexa_capital_account = @indexa_capital_item.indexa_capital_accounts.find_by(id: indexa_capital_account_id)
@@ -314,28 +323,7 @@ class IndexaCapitalItemsController < ApplicationController
provider = indexa_capital_item.indexa_capital_provider
return unless provider
- accounts_data = provider.list_accounts
-
- accounts_data.each do |account_data|
- account_number = account_data[:account_number].to_s
- next if account_number.blank?
-
- # Fetch current balance from performance endpoint
- balance = provider.get_account_balance(account_number: account_number)
- account_data[:current_balance] = balance
- rescue => e
- Rails.logger.warn "IndexaCapitalItemsController - Failed to fetch balance for #{account_number}: #{e.message}"
- end
-
- accounts_data.each do |account_data|
- account_number = account_data[:account_number].to_s
- next if account_number.blank?
-
- 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)
- end
+ IndexaCapitalItem::Importer.new(indexa_capital_item, indexa_capital_provider: provider).import_accounts
rescue Provider::IndexaCapital::AuthenticationError => e
Rails.logger.error "IndexaCapitalItemsController - Auth failed during sync: #{e.message}"
flash.now[:alert] = t("indexa_capital_items.select_accounts.api_error", message: e.message)
diff --git a/app/controllers/monobank_items_controller.rb b/app/controllers/monobank_items_controller.rb
index ee9fbe7d25..a1cc10f6f2 100644
--- a/app/controllers/monobank_items_controller.rb
+++ b/app/controllers/monobank_items_controller.rb
@@ -343,9 +343,6 @@ class MonobankItemsController < ApplicationController
# Create and sync a Sure account from a Monobank account snapshot.
def create_account_from_monobank(monobank_account, account_type)
- # Linking an account clears any prior skip so a future unlink re-prompts for setup.
- monobank_account.update!(ignored: false) if monobank_account.ignored?
-
balance = monobank_account.current_balance || 0
subtype = if account_type == "Depository" && monobank_account.suggested_account_type == account_type
monobank_account.suggested_subtype
diff --git a/app/controllers/redbark_items_controller.rb b/app/controllers/redbark_items_controller.rb
index 5d81c76fba..fd7aacb52f 100644
--- a/app/controllers/redbark_items_controller.rb
+++ b/app/controllers/redbark_items_controller.rb
@@ -114,7 +114,6 @@ class RedbarkItemsController < ApplicationController
end
redbark_account.ensure_account_provider!(account)
- redbark_account.update!(ignored: false)
redbark_item.sync_later unless redbark_item.syncing?
redirect_to account_path(account), notice: t(".success", account_name: account.name)
@@ -163,9 +162,7 @@ class RedbarkItemsController < ApplicationController
ActiveRecord::Base.transaction do
account = create_account_from_redbark(redbark_account, accountable_type, config)
redbark_account.ensure_account_provider!(account)
- attributes = { ignored: false }
- attributes[:sync_start_date] = config[:sync_start_date] if config[:sync_start_date].present?
- redbark_account.update!(attributes)
+ redbark_account.update!(sync_start_date: config[:sync_start_date]) if config[:sync_start_date].present?
end
created_count += 1
rescue => e
@@ -259,7 +256,6 @@ class RedbarkItemsController < ApplicationController
)
redbark_account.ensure_account_provider!(account)
- redbark_account.update!(ignored: false)
account
end
diff --git a/app/controllers/up_items_controller.rb b/app/controllers/up_items_controller.rb
index 752f2a742a..48b3a7bad7 100644
--- a/app/controllers/up_items_controller.rb
+++ b/app/controllers/up_items_controller.rb
@@ -354,9 +354,6 @@ class UpItemsController < ApplicationController
# Create and sync a Sure account from an Up account snapshot.
def create_account_from_up(up_account, account_type)
- # Linking an account clears any prior skip so a future unlink re-prompts for setup.
- up_account.update!(ignored: false) if up_account.ignored?
-
balance = up_account.current_balance || 0
balance = balance.abs if account_type == "Loan"
subtype = if account_type == "Depository" && up_account.suggested_account_type == account_type
diff --git a/app/models/account_provider.rb b/app/models/account_provider.rb
index 61f983a2f3..39dcfd2836 100644
--- a/app/models/account_provider.rb
+++ b/app/models/account_provider.rb
@@ -22,6 +22,9 @@ class AccountProvider < ApplicationRecord
# The Sure account and its holdings are untouched and carry on as manual.
after_destroy :destroy_onchain_provider_account, if: :onchain_provider?
+ # Linking an account the user ignored during setup is how they take it back.
+ after_create :stop_ignoring_provider_account, if: -> { provider.respond_to?(:ignored?) }
+
# Returns the provider adapter for this connection
def adapter
Provider::Factory.create_adapter(provider, account: account)
@@ -35,6 +38,12 @@ class AccountProvider < ApplicationRecord
private
+ # Under the provider's row lock, which reloads it: an ignore! that committed
+ # after the provider was loaded is seen, and one still running waits.
+ def stop_ignoring_provider_account
+ provider.with_lock { provider.update!(ignored: false) if provider.ignored? }
+ end
+
def financekit_has_exclusive_writer
# belongs_to :account already reports a missing account; bail out rather
# than dereference it below.
diff --git a/app/models/concerns/ignorable_provider_account.rb b/app/models/concerns/ignorable_provider_account.rb
new file mode 100644
index 0000000000..0b730dc71c
--- /dev/null
+++ b/app/models/concerns/ignorable_provider_account.rb
@@ -0,0 +1,47 @@
+# A provider account the user skipped during setup, for instance one that belongs
+# to someone else but is visible through the same credentials. The row stays so
+# the choice survives re-syncs, but importers neither fetch nor store anything
+# for it. Linking it to a Sure account clears the flag (see AccountProvider).
+#
+# Including models need an `ignored` boolean column and an `account_provider`
+# association, define `ignored_snapshot_reset` with the fetched data to drop, and
+# declare their snapshot writers with `writes_unless_ignored`.
+module IgnorableProviderAccount
+ extend ActiveSupport::Concern
+
+ included do
+ # Unlinked accounts that still need a setup decision.
+ scope :needs_setup, -> { left_joins(:account_provider).where(account_providers: { id: nil }, ignored: false) }
+ end
+
+ class_methods do
+ # Runs each named writer through write_unless_ignored, so every caller is
+ # covered, including an import that read the account before it was ignored.
+ def writes_unless_ignored(*writers)
+ prepend(Module.new do
+ writers.each do |writer|
+ define_method(writer) { |*args, **kwargs, &block| write_unless_ignored { super(*args, **kwargs, &block) } }
+ end
+ end)
+ end
+ end
+
+ # Returns false, and changes nothing, when the account is linked: unlink it first.
+ # The row lock reloads the account, so a link committed meanwhile is seen.
+ def ignore!
+ with_lock do
+ next false if account_provider.present?
+
+ update!(ignored: true, **ignored_snapshot_reset)
+ end
+ end
+
+ # Runs the block (a snapshot write) under the row lock unless the account is
+ # ignored by then, so data fetched before an ignore! is not written after it.
+ # An ignore! arriving meanwhile waits for the lock. Returns false when skipped.
+ def write_unless_ignored
+ return yield if new_record?
+
+ with_lock { ignored? ? false : yield }
+ end
+end
diff --git a/app/models/concerns/sync_stats/collector.rb b/app/models/concerns/sync_stats/collector.rb
index abcf43bc4e..1fd3342ffa 100644
--- a/app/models/concerns/sync_stats/collector.rb
+++ b/app/models/concerns/sync_stats/collector.rb
@@ -44,7 +44,8 @@ module SyncStats
end
end
- unlinked_count = total_accounts - linked_count
+ # An account the user chose to ignore (never a linked one) is not outstanding setup work.
+ unlinked_count = total_accounts - linked_count - provider_accounts.count { |pa| pa.try(:ignored?) }
setup_stats = {
"total_accounts" => total_accounts,
diff --git a/app/models/enable_banking_account.rb b/app/models/enable_banking_account.rb
index c211bb9316..b74e9d9644 100644
--- a/app/models/enable_banking_account.rb
+++ b/app/models/enable_banking_account.rb
@@ -1,5 +1,5 @@
class EnableBankingAccount < ApplicationRecord
- include CurrencyNormalizable, Encryptable
+ include CurrencyNormalizable, Encryptable, IgnorableProviderAccount
# Encrypt raw payloads if ActiveRecord encryption is configured
if encryption_ready?
@@ -131,6 +131,13 @@ class EnableBankingAccount < ApplicationRecord
)
end
+ # Keeps the session-scoped identifiers current without storing anything else,
+ # so an ignored account can still sync once the user links it.
+ def refresh_session_identifiers!(account_snapshot)
+ snapshot = account_snapshot.with_indifferent_access
+ update!(account_id: snapshot[:uid], identification_hashes: snapshot[:identification_hashes] || identification_hashes)
+ end
+
def upsert_enable_banking_transactions_snapshot!(transactions_snapshot)
assign_attributes(
raw_transactions_payload: transactions_snapshot
@@ -139,8 +146,14 @@ class EnableBankingAccount < ApplicationRecord
save!
end
+ writes_unless_ignored :upsert_enable_banking_snapshot!, :upsert_enable_banking_transactions_snapshot!
+
private
+ def ignored_snapshot_reset
+ { current_balance: nil, raw_payload: nil, raw_transactions_payload: nil }
+ end
+
def build_account_name(snapshot)
# Try to build a meaningful name from the account data
raw_account_id = snapshot[:account_id]
diff --git a/app/models/enable_banking_item.rb b/app/models/enable_banking_item.rb
index c211e85f81..9c1cee3ac1 100644
--- a/app/models/enable_banking_item.rb
+++ b/app/models/enable_banking_item.rb
@@ -278,7 +278,7 @@ class EnableBankingItem < ApplicationRecord
end
def unlinked_accounts_count
- enable_banking_accounts.left_joins(:account_provider).where(account_providers: { id: nil }).count
+ enable_banking_accounts.needs_setup.count
end
def total_accounts_count
@@ -305,7 +305,7 @@ class EnableBankingItem < ApplicationRecord
else
total_accounts = enable_banking_accounts.count
linked_count = accounts.count
- unlinked_count = total_accounts - linked_count
+ unlinked_count = unlinked_accounts_count
if total_accounts == 0
"No accounts found"
@@ -434,8 +434,10 @@ class EnableBankingItem < ApplicationRecord
next unless uid.present?
enable_banking_account = enable_banking_accounts.find_or_initialize_by(uid: uid)
- enable_banking_account.upsert_enable_banking_snapshot!(account_data)
- enable_banking_account.save!
+ # An ignored account keeps only its session identifiers current.
+ unless enable_banking_account.upsert_enable_banking_snapshot!(account_data)
+ enable_banking_account.refresh_session_identifiers!(account_data)
+ end
end
end
end
diff --git a/app/models/enable_banking_item/importer.rb b/app/models/enable_banking_item/importer.rb
index de62d9e356..aa392db527 100644
--- a/app/models/enable_banking_item/importer.rb
+++ b/app/models/enable_banking_item/importer.rb
@@ -303,13 +303,16 @@ class EnableBankingItem::Importer
# DBIT indicates a negative balance (money owed/withdrawn).
parsed_amount = -parsed_amount if indicator == "DBIT"
- enable_banking_account.update!(
- current_balance: parsed_amount,
- currency: balance_currency(balance) || enable_banking_account.currency,
- balance_evidence_verified: tiebreak_stage.nil? || VERIFIED_TIEBREAK_STAGES.include?(tiebreak_stage)
- )
+ # Skipped when the account was unlinked and ignored during the fetch.
+ written = enable_banking_account.write_unless_ignored do
+ enable_banking_account.update!(
+ current_balance: parsed_amount,
+ currency: balance_currency(balance) || enable_banking_account.currency,
+ balance_evidence_verified: tiebreak_stage.nil? || VERIFIED_TIEBREAK_STAGES.include?(tiebreak_stage)
+ )
+ end
# Only now is the chosen-currency balance known to be the one in use.
- capture_skipped_currency_balances(enable_banking_account, currency, skipped)
+ capture_skipped_currency_balances(enable_banking_account, currency, skipped) if written
true
rescue Provider::EnableBanking::EnableBankingError => e
@@ -935,7 +938,9 @@ class EnableBankingItem::Importer
transactions_count = all_transactions.count
- existing_transactions = enable_banking_account.raw_transactions_payload.to_a
+ # A copy: pruning the stored array in place would leave the record dirty,
+ # and the guarded write below cannot lock a record with unsaved changes.
+ existing_transactions = enable_banking_account.raw_transactions_payload.to_a.dup
removed_pending = false
diff --git a/app/models/enable_banking_item/syncer.rb b/app/models/enable_banking_item/syncer.rb
index cc1448d610..26ecfb62d2 100644
--- a/app/models/enable_banking_item/syncer.rb
+++ b/app/models/enable_banking_item/syncer.rb
@@ -50,7 +50,7 @@ class EnableBankingItem::Syncer
sync.update!(status_text: "Checking account configuration...") if sync.respond_to?(:status_text)
collect_setup_stats(sync, provider_accounts: enable_banking_item.enable_banking_accounts.includes(:account_provider, :account))
- unlinked_accounts = enable_banking_item.enable_banking_accounts.left_joins(:account_provider).where(account_providers: { id: nil })
+ unlinked_accounts = enable_banking_item.enable_banking_accounts.needs_setup
if unlinked_accounts.any?
enable_banking_item.update!(pending_account_setup: true)
diff --git a/app/models/fio_item/syncer.rb b/app/models/fio_item/syncer.rb
index d40c083013..c4a26a3a7d 100644
--- a/app/models/fio_item/syncer.rb
+++ b/app/models/fio_item/syncer.rb
@@ -30,11 +30,6 @@ class FioItem::Syncer
sync.update!(status_text: I18n.t("fio_item.sync.status.checking_setup")) if sync.respond_to?(:status_text)
collect_setup_stats(sync, provider_accounts: fio_item.fio_accounts)
- # The collector derives unlinked as total minus linked, which counts an account the
- # user skipped during setup as outstanding work. FioItem's own counts exclude it, and
- # the status summary reads these stats in preference to them, so it would otherwise
- # keep reporting setup the user has already declined.
- merge_sync_stats(sync, "unlinked_accounts" => fio_item.unlinked_accounts_count)
linked_accounts = fio_item.fio_accounts.joins(:account_provider)
unlinked_accounts = fio_item.fio_accounts.needs_setup
diff --git a/app/models/indexa_capital_account.rb b/app/models/indexa_capital_account.rb
index 2af332b4eb..1b81596ac7 100644
--- a/app/models/indexa_capital_account.rb
+++ b/app/models/indexa_capital_account.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
class IndexaCapitalAccount < ApplicationRecord
- include CurrencyNormalizable, Encryptable
+ include CurrencyNormalizable, Encryptable, IgnorableProviderAccount
include IndexaCapitalAccount::DataHelpers
# Encrypt raw payloads if ActiveRecord encryption is configured
@@ -92,8 +92,14 @@ class IndexaCapitalAccount < ApplicationRecord
)
end
+ writes_unless_ignored :upsert_from_indexa_capital!, :upsert_holdings_snapshot!, :upsert_activities_snapshot!
+
private
+ def ignored_snapshot_reset
+ { current_balance: nil, raw_payload: nil, raw_holdings_payload: [], raw_activities_payload: [] }
+ end
+
def enqueue_connection_cleanup
return unless indexa_capital_item
return unless indexa_capital_authorization_id.present?
diff --git a/app/models/indexa_capital_item.rb b/app/models/indexa_capital_item.rb
index 8ca243efa4..98eb7f593c 100644
--- a/app/models/indexa_capital_item.rb
+++ b/app/models/indexa_capital_item.rb
@@ -109,9 +109,9 @@ class IndexaCapitalItem < ApplicationRecord
indexa_capital_accounts.joins(:account_provider)
end
- # Unlinked accounts (no AccountProvider association)
+ # Unlinked accounts that still need a setup decision (ignored ones are left out)
def unlinked_indexa_capital_accounts
- indexa_capital_accounts.left_joins(:account_provider).where(account_providers: { id: nil })
+ indexa_capital_accounts.needs_setup
end
def sync_status_summary
@@ -133,7 +133,7 @@ class IndexaCapitalItem < ApplicationRecord
end
def unlinked_accounts_count
- indexa_capital_accounts.left_joins(:account_provider).where(account_providers: { id: nil }).count
+ unlinked_indexa_capital_accounts.count
end
def total_accounts_count
diff --git a/app/models/indexa_capital_item/importer.rb b/app/models/indexa_capital_item/importer.rb
index 2b2368710b..28368fa219 100644
--- a/app/models/indexa_capital_item/importer.rb
+++ b/app/models/indexa_capital_item/importer.rb
@@ -43,6 +43,34 @@ class IndexaCapitalItem::Importer
raise
end
+ # Fetch the account list and refresh every account the user has not ignored.
+ # Also used by the controller to show fresh balances in the account picker.
+ 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
+
+ # Collected up front: an account the provider still lists must not be pruned
+ # because importing it failed.
+ upstream_account_ids = accounts_data.filter_map { |account_data| account_data[:account_number]&.to_s }
+
+ accounts_data.each do |account_data|
+ import_account(account_data)
+ 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
+
private
def stats
@@ -55,35 +83,17 @@ class IndexaCapitalItem::Importer
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?
+ indexa_capital_account = indexa_capital_item.indexa_capital_accounts.find_or_initialize_by(
+ indexa_capital_account_id: account_number
+ )
+ # Skip the balance call for an ignored account; the guarded upsert below
+ # covers one ignored while the call is in flight.
+ return if indexa_capital_account.ignored?
+
# Fetch current balance from performance endpoint
begin
balance = indexa_capital_provider.get_account_balance(account_number: account_number)
@@ -93,11 +103,7 @@ class IndexaCapitalItem::Importer
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)
+ return unless indexa_capital_account.upsert_from_indexa_capital!(account_data)
stats["accounts_imported"] = stats.fetch("accounts_imported", 0) + 1
end
@@ -122,9 +128,8 @@ class IndexaCapitalItem::Importer
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)
+ # Skipped when the account was unlinked and ignored during the fetch.
+ if holdings_array.any? && indexa_capital_account.upsert_holdings_snapshot!(holdings_array.map { |h| sdk_object_to_hash(h) })
stats["holdings_found"] = stats.fetch("holdings_found", 0) + holdings_array.size
end
rescue => e
diff --git a/app/views/enable_banking_items/setup_accounts.html.erb b/app/views/enable_banking_items/setup_accounts.html.erb
index aea994a7f1..6fc10198de 100644
--- a/app/views/enable_banking_items/setup_accounts.html.erb
+++ b/app/views/enable_banking_items/setup_accounts.html.erb
@@ -31,6 +31,7 @@
<li><strong><%= label %></strong></li>
<% end %>
</ul>
+ <p class="text-xs text-secondary mt-2"><%= t(".skip_notice") %></p>
</div>
</div>
</div>
diff --git a/app/views/indexa_capital_items/setup_accounts.html.erb b/app/views/indexa_capital_items/setup_accounts.html.erb
index b73b3ed5f1..fb16386c31 100644
--- a/app/views/indexa_capital_items/setup_accounts.html.erb
+++ b/app/views/indexa_capital_items/setup_accounts.html.erb
@@ -17,6 +17,9 @@
<p class="text-sm text-primary">
<%= t("indexa_capital_items.setup_accounts.instructions") %>
</p>
+ <p class="text-sm text-secondary mt-1">
+ <%= t("indexa_capital_items.setup_accounts.skip_notice") %>
+ </p>
</div>
</div>
</div>
@@ -36,6 +39,7 @@
<% @unlinked_accounts.each do |indexa_capital_account| %>
<div class="border border-primary rounded-lg p-4 hover:bg-surface transition-colors">
+ <%= hidden_field_tag "setup_account_ids[]", indexa_capital_account.id, id: nil %>
<div class="flex items-center gap-3">
<input type="checkbox"
id="account_<%= indexa_capital_account.id %>"
diff --git a/config/locales/views/enable_banking_items/en.yml b/config/locales/views/enable_banking_items/en.yml
index 1a86db39f8..1a9a666f51 100644
--- a/config/locales/views/enable_banking_items/en.yml
+++ b/config/locales/views/enable_banking_items/en.yml
@@ -20,7 +20,7 @@ en:
success: Successfully connected to your bank. Your accounts are syncing.
unexpected_error: An unexpected error occurred. Please try again.
complete_account_setup:
- all_skipped: All accounts were skipped. You can set them up later on the accounts page.
+ all_skipped: All accounts were skipped. Link one to an account later to start syncing it.
no_accounts: No accounts available to set up.
success: Successfully created %{count} accounts!
create:
@@ -66,6 +66,7 @@ en:
title: Set Up Your Enable Banking Accounts
header_subtitle: Choose the correct account types for your imported accounts
choose_account_type: "Choose the correct account type for each Enable Banking account:"
+ skip_notice: "Skipped accounts are remembered: Sure stops importing them until you link them to an account."
historical_data_range: "Historical Data Range:"
sync_start_date_label: "Start syncing transactions from:"
sync_start_date_help: Optional. Leave it blank to import as much history as your bank provides; how far back that goes depends on the bank. If you pick a date, transactions before it are not imported.
diff --git a/config/locales/views/indexa_capital_items/en.yml b/config/locales/views/indexa_capital_items/en.yml
index 774bca112a..616a6b858d 100644
--- a/config/locales/views/indexa_capital_items/en.yml
+++ b/config/locales/views/indexa_capital_items/en.yml
@@ -180,6 +180,7 @@ en:
fetch_failed: "Failed to Fetch Accounts"
import_selected: "Import selected accounts"
instructions: "Select the accounts you want to import from IndexaCapital. You can choose multiple accounts."
+ skip_notice: "Unchecked accounts are skipped: Sure stops fetching them until you link them to an account."
no_accounts: "No unlinked accounts found from this IndexaCapital connection."
no_accounts_to_setup: "No Accounts to Set Up"
no_api_key: "IndexaCapital credentials are not configured. Please check your connection settings."
diff --git a/db/migrate/20261116120000_add_ignored_to_indexa_capital_and_enable_banking_accounts.rb b/db/migrate/20261116120000_add_ignored_to_indexa_capital_and_enable_banking_accounts.rb
new file mode 100644
index 0000000000..09b54d5606
--- /dev/null
+++ b/db/migrate/20261116120000_add_ignored_to_indexa_capital_and_enable_banking_accounts.rb
@@ -0,0 +1,6 @@
+class AddIgnoredToIndexaCapitalAndEnableBankingAccounts < ActiveRecord::Migration[8.1]
+ def change
+ add_column :indexa_capital_accounts, :ignored, :boolean, default: false, null: false
+ add_column :enable_banking_accounts, :ignored, :boolean, default: false, null: false
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 81a8241677..0920665b2e 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[8.1].define(version: 2026_11_14_233000) do
+ActiveRecord::Schema[8.1].define(version: 2026_11_16_120000) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"
enable_extension "pgcrypto"
@@ -654,6 +654,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_233000) do
t.uuid "enable_banking_item_id", null: false
t.string "iban"
t.jsonb "identification_hashes", default: []
+ t.boolean "ignored", default: false, null: false
t.jsonb "institution_metadata"
t.string "name"
t.string "product"
@@ -1454,6 +1455,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_233000) do
t.datetime "created_at", null: false
t.string "currency"
t.decimal "current_balance", precision: 19, scale: 4
+ t.boolean "ignored", default: false, null: false
t.string "indexa_capital_account_id"
t.string "indexa_capital_authorization_id"
t.uuid "indexa_capital_item_id", null: false
diff --git a/test/controllers/enable_banking_items_controller_test.rb b/test/controllers/enable_banking_items_controller_test.rb
index 04909a596c..2952c11d2c 100644
--- a/test/controllers/enable_banking_items_controller_test.rb
+++ b/test/controllers/enable_banking_items_controller_test.rb
@@ -344,6 +344,31 @@ class EnableBankingItemsControllerTest < ActionDispatch::IntegrationTest
assert_equal "active", orphan.reload.status
end
+ test "setup_accounts does not offer an ignored account" do
+ mine = @item.enable_banking_accounts.create!(name: "Mine", uid: "hash_mine", currency: "EUR")
+ theirs = @item.enable_banking_accounts.create!(name: "Theirs", uid: "hash_theirs", currency: "EUR")
+ theirs.ignore!
+
+ get setup_accounts_enable_banking_item_url(@item)
+
+ assert_response :success
+ assert_select "select[name=?]", "account_types[#{mine.id}]"
+ assert_select "select[name=?]", "account_types[#{theirs.id}]", count: 0
+ end
+
+ test "complete_account_setup remembers a skipped account as ignored" do
+ theirs = @item.enable_banking_accounts.create!(name: "Theirs", uid: "hash_theirs", currency: "EUR", current_balance: 50)
+
+ assert_no_difference "Account.count" do
+ post complete_account_setup_enable_banking_item_url(@item), params: { account_types: { theirs.id => "skip" } }
+ end
+
+ assert_redirected_to accounts_path
+ assert theirs.reload.ignored?
+ assert_nil theirs.current_balance
+ assert_not @item.reload.pending_account_setup?
+ end
+
# The modal's form is a plain form_with, so the date field's label and help
# must be rendered as elements rather than passed as builder options (which
# end up as unknown attributes on the input).
diff --git a/test/controllers/indexa_capital_items_controller_test.rb b/test/controllers/indexa_capital_items_controller_test.rb
index cd525a35cf..d5228036a9 100644
--- a/test/controllers/indexa_capital_items_controller_test.rb
+++ b/test/controllers/indexa_capital_items_controller_test.rb
@@ -190,4 +190,75 @@ class IndexaCapitalItemsControllerTest < ActionDispatch::IntegrationTest
assert_select "turbo-frame#modal turbo-stream[action=redirect][target=?]", settings_providers_path
assert_equal I18n.t("indexa_capital_items.select_accounts.no_credentials_configured"), flash[:alert]
end
+
+ test "setup_accounts does not offer an ignored account" do
+ indexa_capital_accounts(:pension_plan).ignore!
+
+ get setup_accounts_indexa_capital_item_url(@item)
+
+ assert_response :success
+ assert_select "input[name='account_ids[]'][value=?]", indexa_capital_accounts(:mutual_fund).id
+ assert_select "input[name='account_ids[]'][value=?]", indexa_capital_accounts(:pension_plan).id, count: 0
+ end
+
+ test "complete_account_setup ignores the accounts the user left unchecked" do
+ mutual_fund = indexa_capital_accounts(:mutual_fund)
+ pension_plan = indexa_capital_accounts(:pension_plan)
+
+ assert_difference "Account.count", 1 do
+ post complete_account_setup_indexa_capital_item_url(@item), params: {
+ setup_account_ids: [ mutual_fund.id, pension_plan.id ],
+ account_ids: [ mutual_fund.id ]
+ }
+ end
+
+ assert_redirected_to accounts_path
+ assert_not_nil mutual_fund.reload.current_account
+ assert_not mutual_fund.ignored?
+ assert pension_plan.reload.ignored?
+ assert_nil pension_plan.current_account
+ end
+
+ test "complete_account_setup with every account unchecked ignores them all" do
+ ids = [ indexa_capital_accounts(:mutual_fund).id, indexa_capital_accounts(:pension_plan).id ]
+ @item.update!(pending_account_setup: true)
+
+ assert_no_difference "Account.count" do
+ post complete_account_setup_indexa_capital_item_url(@item), params: { setup_account_ids: ids }
+ end
+
+ assert_redirected_to accounts_path
+ assert_equal I18n.t("indexa_capital_items.complete_account_setup.all_skipped"), flash[:notice]
+ assert @item.indexa_capital_accounts.where(id: ids).all?(&:ignored?)
+ assert_not @item.reload.pending_account_setup?
+ end
+
+ test "select accounts does not fetch or refresh an ignored account" do
+ pension_plan = indexa_capital_accounts(:pension_plan)
+ pension_plan.ignore!
+ Provider::IndexaCapital.any_instance.stubs(:list_accounts).returns([
+ { account_number: "LPYH3MCQ", name: "Mutual Fund", type: "mutual", status: "active", currency: "EUR" },
+ { account_number: "DCU8HWEP", name: "Renamed", type: "pension", status: "active", currency: "EUR" }
+ ])
+ Provider::IndexaCapital.any_instance.expects(:get_account_balance).with(account_number: "LPYH3MCQ").returns(100)
+ Provider::IndexaCapital.any_instance.expects(:get_account_balance).with(account_number: "DCU8HWEP").never
+
+ assert_no_changes -> { pension_plan.reload.attributes } do
+ get select_accounts_indexa_capital_items_url
+ end
+
+ assert_response :success
+ assert_equal 100, indexa_capital_accounts(:mutual_fund).reload.current_balance
+ end
+
+ test "linking an ignored account to an existing Sure account stops ignoring it" do
+ pension_plan = indexa_capital_accounts(:pension_plan)
+ pension_plan.ignore!
+ manual_account = Account.create!(family: @family, name: "Manual Pension", balance: 0, currency: "EUR", accountable: Investment.new)
+
+ post link_existing_account_indexa_capital_items_url, params: { account_id: manual_account.id, indexa_capital_account_id: pension_plan.id }
+
+ assert_equal manual_account, pension_plan.reload.current_account
+ assert_not pension_plan.ignored?
+ end
end
diff --git a/test/models/account_provider_test.rb b/test/models/account_provider_test.rb
index d0169e134c..15ec23c665 100644
--- a/test/models/account_provider_test.rb
+++ b/test/models/account_provider_test.rb
@@ -174,4 +174,22 @@ class AccountProviderTest < ActiveSupport::TestCase
# CoinStats provider accounts should be destroyed to avoid orphaned records
assert_not CoinstatsAccount.exists?(coinstats_account_id)
end
+
+ test "linking an ignored provider account stops ignoring it" do
+ indexa_account = indexa_capital_accounts(:pension_plan)
+ indexa_account.ignore!
+
+ AccountProvider.create!(account: @account, provider: indexa_account)
+
+ assert_not indexa_account.reload.ignored?
+ end
+
+ test "linking stops ignoring an account that was ignored after it was loaded" do
+ indexa_account = indexa_capital_accounts(:pension_plan)
+ IndexaCapitalAccount.find(indexa_account.id).ignore!
+
+ AccountProvider.create!(account: @account, provider: indexa_account)
+
+ assert_not indexa_account.reload.ignored?
+ end
end
diff --git a/test/models/enable_banking_account_test.rb b/test/models/enable_banking_account_test.rb
index d638e0ec05..30a5cea41a 100644
--- a/test/models/enable_banking_account_test.rb
+++ b/test/models/enable_banking_account_test.rb
@@ -149,4 +149,48 @@ class EnableBankingAccountTest < ActiveSupport::TestCase
})
assert_equal [], @account.reload.identification_hashes
end
+
+ test "ignore! keeps the account's identity but drops what was fetched for it" do
+ @account.update!(current_balance: 1234.56, raw_payload: { "uid" => "uid_1", "iban" => "FR7612345" },
+ raw_transactions_payload: [ { "transaction_id" => "t1" } ])
+
+ assert @account.ignore!
+
+ @account.reload
+ assert @account.ignored?
+ assert_equal "hash_abc123", @account.uid
+ assert_equal "Mon compte", @account.name
+ assert_nil @account.current_balance
+ assert_nil @account.raw_payload
+ assert_nil @account.raw_transactions_payload
+ end
+
+ test "ignore! refuses an account that is linked to a Sure account" do
+ @account.update!(current_balance: 10)
+ AccountProvider.create!(account: accounts(:depository), provider: @account)
+
+ assert_not @account.ignore!
+ assert_not @account.reload.ignored?
+ assert_equal 10, @account.current_balance
+ end
+
+ test "needs_setup leaves out linked and ignored accounts" do
+ linked = EnableBankingAccount.create!(enable_banking_item: @item, name: "Linked", uid: "hash_linked", currency: "EUR")
+ AccountProvider.create!(account: accounts(:depository), provider: linked)
+
+ assert_equal [ @account ], @item.enable_banking_accounts.needs_setup.to_a
+
+ @account.ignore!
+ assert_empty @item.enable_banking_accounts.needs_setup
+ end
+
+ test "snapshot writers skip an account ignored after it was loaded" do
+ stale = EnableBankingAccount.find(@account.id)
+ @account.ignore!
+
+ assert_no_changes -> { @account.reload.attributes } do
+ assert_not stale.upsert_enable_banking_snapshot!(uid: "uid_1", identification_hash: "hash_abc123", name: "Renamed", currency: "EUR")
+ assert_not stale.upsert_enable_banking_transactions_snapshot!([ { "transaction_id" => "t1" } ])
+ end
+ end
end
diff --git a/test/models/enable_banking_item/importer_ignored_test.rb b/test/models/enable_banking_item/importer_ignored_test.rb
new file mode 100644
index 0000000000..82a5028361
--- /dev/null
+++ b/test/models/enable_banking_item/importer_ignored_test.rb
@@ -0,0 +1,96 @@
+require "test_helper"
+
+class EnableBankingItem::ImporterIgnoredTest < ActiveSupport::TestCase
+ setup do
+ @item = EnableBankingItem.create!(
+ family: families(:dylan_family),
+ name: "Test EB",
+ country_code: "ES",
+ application_id: "test_app_id",
+ client_certificate: "test_cert",
+ session_id: "test_session",
+ session_expires_at: 1.day.from_now
+ )
+ @ignored = @item.enable_banking_accounts.create!(name: "Theirs", uid: "hash_theirs", account_id: "uid-old", currency: "EUR")
+ @ignored.ignore!
+ @importer = EnableBankingItem::Importer.new(@item, enable_banking_provider: mock("enable_banking_provider"))
+ end
+
+ test "a sync refreshes only the session UID of an ignored account" do
+ @importer.stubs(:fetch_session_data).returns(
+ accounts: [ { uid: "uid-new", identification_hash: "hash_theirs", currency: "EUR", name: "Renamed" } ]
+ )
+
+ assert_no_changes -> { @ignored.reload.attributes.except("account_id", "updated_at") } do
+ @importer.import
+ end
+ assert_equal "uid-new", @ignored.account_id
+ end
+
+ test "an account ignored before a re-authorization syncs with the new session UID once linked" do
+ @item.stubs(:enable_banking_provider).returns(stub(create_session: {
+ session_id: "sess-new",
+ accounts: [ { uid: "uid-new", identification_hash: "hash_theirs", currency: "EUR", name: "Theirs" } ]
+ }))
+ @item.complete_authorization(code: "code")
+ account = Account.create!(family: @item.family, name: "Theirs", balance: 0, currency: "EUR", accountable: Depository.new)
+ AccountProvider.create!(account: account, provider: @ignored)
+
+ provider = mock("enable_banking_provider")
+ provider.expects(:get_account_transactions).with(has_entry(account_id: "uid-new")).at_least_once.returns(transactions: [])
+ provider.expects(:get_account_balances).with(has_entry(account_id: "uid-new")).returns(balances: [])
+ importer = EnableBankingItem::Importer.new(@item.reload, enable_banking_provider: provider)
+ # GET /sessions can list accounts as bare session UIDs, which carry no identification hash.
+ importer.stubs(:fetch_session_data).returns(accounts: [ "uid-new" ])
+
+ importer.import
+ end
+
+ test "an account unlinked and ignored while its transactions are being fetched is not written back" do
+ mine = linked_account("hash_mine")
+ skip_mine = -> { unlink_and_ignore(mine) }
+ @importer.stubs(:include_pending?).returns(false)
+ @importer.define_singleton_method(:fetch_paginated_transactions) do |*, **|
+ skip_mine.call
+ [ { transaction_id: "tx1", booking_date: Date.current.to_s, transaction_amount: { amount: "15.00", currency: "EUR" }, credit_debit_indicator: "DBIT" } ]
+ end
+
+ @importer.send(:fetch_and_store_transactions, mine)
+
+ mine.reload
+ assert mine.ignored?
+ assert_nil mine.raw_transactions_payload
+ end
+
+ test "an account unlinked and ignored while its balance is being fetched is not written back" do
+ mine = linked_account("hash_mine")
+ skip_mine = -> { unlink_and_ignore(mine) }
+ provider = Object.new
+ provider.define_singleton_method(:get_account_balances) do |**|
+ skip_mine.call
+ { balances: [ { balance_type: "ITBD", balance_amount: { amount: "50.00", currency: "EUR" }, credit_debit_indicator: "CRDT" } ] }
+ end
+ importer = EnableBankingItem::Importer.new(@item, enable_banking_provider: provider)
+
+ importer.send(:fetch_and_update_balance, mine)
+
+ mine.reload
+ assert mine.ignored?
+ assert_nil mine.current_balance
+ end
+
+ private
+
+ def linked_account(uid)
+ enable_banking_account = @item.enable_banking_accounts.create!(name: "Mine", uid: uid, account_id: "uid-mine", currency: "EUR", current_balance: 10)
+ account = Account.create!(family: @item.family, name: "Mine", balance: 10, currency: "EUR", accountable: Depository.new)
+ AccountProvider.create!(account: account, provider: enable_banking_account)
+ enable_banking_account
+ end
+
+ # What another request does while a sync is fetching this account.
+ def unlink_and_ignore(enable_banking_account)
+ AccountProvider.find_by(provider: enable_banking_account)&.destroy!
+ EnableBankingAccount.find(enable_banking_account.id).ignore!
+ end
+end
diff --git a/test/models/enable_banking_item/syncer_test.rb b/test/models/enable_banking_item/syncer_test.rb
index f9cfa03ea5..54328b161c 100644
--- a/test/models/enable_banking_item/syncer_test.rb
+++ b/test/models/enable_banking_item/syncer_test.rb
@@ -29,6 +29,18 @@ class EnableBankingItem::SyncerTest < ActiveSupport::TestCase
"Expired session should be a graceful reconnect state, not a red sync error"
end
+ test "ignored accounts do not leave the connection waiting for setup" do
+ @item.update!(session_expires_at: 1.day.from_now)
+ @item.enable_banking_accounts.create!(name: "Theirs", uid: "hash_theirs", currency: "EUR").ignore!
+ @item.stubs(:import_latest_enable_banking_data).returns(success: true)
+ sync = Sync.create!(syncable: @item)
+
+ @syncer.perform_sync(sync)
+
+ assert_not @item.reload.pending_account_setup?
+ assert_equal 0, sync.reload.sync_stats["unlinked_accounts"]
+ end
+
test "a truncated full-history fetch is recorded as a data warning on the sync" do
@item.update!(session_expires_at: 1.day.from_now)
@item.stubs(:import_latest_enable_banking_data).returns(success: true, transactions_truncated: 1)
diff --git a/test/models/enable_banking_item_test.rb b/test/models/enable_banking_item_test.rb
index 39dea8d1df..9e28a06818 100644
--- a/test/models/enable_banking_item_test.rb
+++ b/test/models/enable_banking_item_test.rb
@@ -292,4 +292,63 @@ class EnableBankingItemTest < ActiveSupport::TestCase
assert_equal({}, @item.build_psu_headers)
end
+
+ test "an ignored account no longer needs setup" do
+ @item.save!
+ open_account = @item.enable_banking_accounts.create!(name: "Mine", uid: "hash_mine", currency: "EUR")
+ @item.enable_banking_accounts.create!(name: "Theirs", uid: "hash_theirs", currency: "EUR").ignore!
+ Sync.create!(syncable: @item)
+
+ assert_equal 1, @item.unlinked_accounts_count
+ assert_equal "0 synced, 1 need setup", @item.sync_status_summary
+
+ open_account.ignore!
+ assert_equal 0, @item.unlinked_accounts_count
+ assert_equal "0 accounts synced", @item.sync_status_summary
+ end
+
+ test "re-authorizing refreshes only the session identifiers of an ignored account" do
+ @item.save!
+ ignored = @item.enable_banking_accounts.create!(name: "Theirs", uid: "hash_theirs", account_id: "uid_old", currency: "EUR")
+ ignored.ignore!
+ provider = mock("enable_banking_provider")
+ provider.stubs(:create_session).returns(
+ session_id: "sess_new",
+ accounts: [
+ { uid: "uid_theirs", identification_hash: "hash_theirs", identification_hashes: [ "hash_theirs", "hash_alt" ],
+ currency: "EUR", name: "Renamed", iban: "FR7600001", balance: { amount: "10.00" } },
+ { uid: "uid_mine", identification_hash: "hash_mine", currency: "EUR", name: "Mine" }
+ ]
+ )
+ @item.stubs(:enable_banking_provider).returns(provider)
+
+ assert_no_changes -> { ignored.reload.attributes.except("account_id", "identification_hashes", "updated_at") } do
+ @item.complete_authorization(code: "code")
+ end
+ assert_equal "uid_theirs", ignored.account_id
+ assert_equal [ "hash_theirs", "hash_alt" ], ignored.identification_hashes
+ assert @item.enable_banking_accounts.exists?(uid: "hash_mine")
+ end
+
+ test "re-authorizing does not write back an account ignored after it was read" do
+ @item.save!
+ account = @item.enable_banking_accounts.create!(name: "Theirs", uid: "hash_theirs", account_id: "uid_old", currency: "EUR")
+ stale = EnableBankingAccount.find(account.id)
+ # Another request ignores the account after the re-authorization has read it.
+ account.ignore!
+ @item.enable_banking_accounts.stubs(:find_or_initialize_by).with(uid: "hash_theirs").returns(stale)
+ @item.stubs(:enable_banking_provider).returns(stub(create_session: {
+ session_id: "sess_new",
+ accounts: [ { uid: "uid_new", identification_hash: "hash_theirs", currency: "EUR", name: "Renamed", iban: "FR7600001" } ]
+ }))
+
+ @item.complete_authorization(code: "code")
+
+ account.reload
+ assert account.ignored?
+ assert_equal "Theirs", account.name
+ assert_nil account.raw_payload
+ assert_nil account.iban
+ assert_equal "uid_new", account.account_id
+ end
end
diff --git a/test/models/indexa_capital_account_test.rb b/test/models/indexa_capital_account_test.rb
index 3b5684cfa2..6ebbe7ca6b 100644
--- a/test/models/indexa_capital_account_test.rb
+++ b/test/models/indexa_capital_account_test.rb
@@ -132,4 +132,60 @@ class IndexaCapitalAccountTest < ActiveSupport::TestCase
assert_includes encrypted, "raw_holdings_payload"
assert_includes encrypted, "raw_activities_payload"
end
+
+ test "ignore! keeps the account's identity but drops what was fetched for it" do
+ @account.update!(raw_payload: { "account_number" => "LPYH3MCQ" }, raw_holdings_payload: [ { "titles" => 1 } ],
+ raw_activities_payload: [ { "id" => "a1" } ])
+
+ assert @account.ignore!
+
+ @account.reload
+ assert @account.ignored?
+ assert_equal "LPYH3MCQ", @account.indexa_capital_account_id
+ assert_equal "Indexa Capital Mutual Fund (LPYH3MCQ)", @account.name
+ assert_nil @account.current_balance
+ assert_nil @account.raw_payload
+ assert_equal [], @account.raw_holdings_payload
+ assert_equal [], @account.raw_activities_payload
+ end
+
+ test "ignore! refuses an account that is linked to a Sure account" do
+ linked_account = Account.create!(family: @family, name: "My Fund", balance: 1000, currency: "EUR", accountable: Investment.new)
+ @account.ensure_account_provider!(linked_account)
+
+ assert_not @account.ignore!
+ assert_not @account.reload.ignored?
+ assert_not_nil @account.current_balance
+ end
+
+ test "needs_setup leaves out linked and ignored accounts" do
+ pension = indexa_capital_accounts(:pension_plan)
+ linked_account = Account.create!(family: @family, name: "My Fund", balance: 1000, currency: "EUR", accountable: Investment.new)
+ @account.ensure_account_provider!(linked_account)
+
+ assert_equal [ pension ], @item.indexa_capital_accounts.needs_setup.to_a
+
+ pension.ignore!
+ assert_empty @item.indexa_capital_accounts.needs_setup
+ end
+
+ test "ignore! sees a link created after the account was loaded" do
+ @account.account_provider # loaded while still unlinked
+ linked_account = Account.create!(family: @family, name: "My Fund", balance: 1000, currency: "EUR", accountable: Investment.new)
+ IndexaCapitalAccount.find(@account.id).ensure_account_provider!(linked_account)
+
+ assert_not @account.ignore!
+ assert_not @account.reload.ignored?
+ end
+
+ test "snapshot writers skip an account ignored after it was loaded" do
+ stale = IndexaCapitalAccount.find(@account.id)
+ @account.ignore!
+
+ assert_no_changes -> { @account.reload.attributes } do
+ assert_not stale.upsert_from_indexa_capital!(account_number: "LPYH3MCQ", name: "Renamed", current_balance: 1)
+ assert_not stale.upsert_holdings_snapshot!([ { "titles" => 1 } ])
+ assert_not stale.upsert_activities_snapshot!([ { "id" => "a1" } ])
+ end
+ end
end
diff --git a/test/models/indexa_capital_item/importer_test.rb b/test/models/indexa_capital_item/importer_test.rb
new file mode 100644
index 0000000000..df222a405e
--- /dev/null
+++ b/test/models/indexa_capital_item/importer_test.rb
@@ -0,0 +1,83 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class IndexaCapitalItem::ImporterTest < ActiveSupport::TestCase
+ setup do
+ @item = indexa_capital_items(:configured_with_token)
+ @ignored = indexa_capital_accounts(:pension_plan)
+ @ignored.ignore!
+ @provider = mock("indexa_capital_provider")
+ @provider.stubs(:list_accounts).returns([
+ { account_number: "LPYH3MCQ", name: "Mutual Fund", type: "mutual", status: "active", currency: "EUR" },
+ { account_number: "DCU8HWEP", name: "Someone else's pension", type: "pension", status: "active", currency: "EUR" }
+ ])
+ end
+
+ test "an ignored account is neither fetched nor updated, and survives the sync" do
+ @provider.expects(:get_account_balance).with(account_number: "LPYH3MCQ").returns(100)
+ @provider.expects(:get_account_balance).with(account_number: "DCU8HWEP").never
+
+ assert_no_changes -> { @ignored.reload.attributes } do
+ IndexaCapitalItem::Importer.new(@item, indexa_capital_provider: @provider).import
+ end
+
+ assert @ignored.reload.ignored?
+ assert_equal 100, indexa_capital_accounts(:mutual_fund).reload.current_balance
+ end
+
+ test "an account ignored while its balance is being fetched is not written back" do
+ mutual_fund = indexa_capital_accounts(:mutual_fund)
+ provider = Object.new
+ provider.define_singleton_method(:list_accounts) do
+ [ { account_number: "LPYH3MCQ", name: "Mutual Fund", type: "mutual", status: "active", currency: "EUR" } ]
+ end
+ provider.define_singleton_method(:get_account_balance) do |account_number:|
+ # The user skips the account from another request while this call is in flight.
+ IndexaCapitalAccount.find(mutual_fund.id).ignore!
+ 100
+ end
+
+ IndexaCapitalItem::Importer.new(@item, indexa_capital_provider: provider).import
+
+ mutual_fund.reload
+ assert mutual_fund.ignored?
+ assert_nil mutual_fund.current_balance
+ assert_nil mutual_fund.raw_payload
+ end
+
+ test "an account unlinked and ignored while its holdings are being fetched is not written back" do
+ mutual_fund = indexa_capital_accounts(:mutual_fund)
+ mutual_fund.ensure_account_provider!(
+ Account.create!(family: @item.family, name: "My Fund", balance: 0, currency: "EUR", accountable: Investment.new)
+ )
+ provider = Object.new
+ provider.define_singleton_method(:list_accounts) do
+ [ { account_number: "LPYH3MCQ", name: "Mutual Fund", type: "mutual", status: "active", currency: "EUR" } ]
+ end
+ provider.define_singleton_method(:get_account_balance) { |account_number:| 100 }
+ provider.define_singleton_method(:get_holdings) do |account_number:|
+ # The user unlinks and skips the account from another request while this call is in flight.
+ AccountProvider.find_by!(provider: mutual_fund).destroy!
+ IndexaCapitalAccount.find(mutual_fund.id).ignore!
+ [ { instrument: { identifier: "IE00B03HCZ61" }, titles: 10, amount: 1000 } ]
+ end
+
+ IndexaCapitalItem::Importer.new(@item, indexa_capital_provider: provider).import
+
+ mutual_fund.reload
+ assert mutual_fund.ignored?
+ assert_equal [], mutual_fund.raw_holdings_payload
+ assert_nil mutual_fund.last_holdings_sync
+ assert_not @item.reload.raw_payload.key?("holdings_found")
+ end
+
+ test "an account still listed upstream is kept when importing it fails" do
+ @provider.stubs(:get_account_balance).returns(100)
+ IndexaCapitalAccount.any_instance.stubs(:upsert_from_indexa_capital!).raises(ActiveRecord::RecordInvalid)
+
+ assert_no_difference -> { @item.indexa_capital_accounts.count } do
+ IndexaCapitalItem::Importer.new(@item, indexa_capital_provider: @provider).import
+ end
+ end
+end
diff --git a/test/models/indexa_capital_item/syncer_test.rb b/test/models/indexa_capital_item/syncer_test.rb
new file mode 100644
index 0000000000..adb343f72a
--- /dev/null
+++ b/test/models/indexa_capital_item/syncer_test.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class IndexaCapitalItem::SyncerTest < ActiveSupport::TestCase
+ setup do
+ @item = indexa_capital_items(:configured_with_token)
+ @item.stubs(:import_latest_indexa_capital_data)
+ end
+
+ test "ignored accounts do not leave the connection waiting for setup" do
+ @item.indexa_capital_accounts.each(&:ignore!)
+ sync = Sync.create!(syncable: @item)
+
+ IndexaCapitalItem::Syncer.new(@item).perform_sync(sync)
+
+ assert_not @item.reload.pending_account_setup?
+ assert_equal 0, sync.reload.sync_stats["unlinked_accounts"]
+ end
+end
diff --git a/test/models/indexa_capital_item_test.rb b/test/models/indexa_capital_item_test.rb
index 39cb0f7ba7..50bc27a0ec 100644
--- a/test/models/indexa_capital_item_test.rb
+++ b/test/models/indexa_capital_item_test.rb
@@ -113,6 +113,21 @@ class IndexaCapitalItemTest < ActiveSupport::TestCase
assert_equal 2, @item.unlinked_accounts_count
end
+ test "an ignored account no longer needs setup" do
+ indexa_capital_accounts(:pension_plan).ignore!
+
+ assert_equal 1, @item.unlinked_accounts_count
+ assert_equal [ indexa_capital_accounts(:mutual_fund) ], @item.unlinked_indexa_capital_accounts.to_a
+ end
+
+ test "sync_status_summary does not ask to set up an ignored account" 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))
+ indexa_capital_accounts(:pension_plan).ignore!
+
+ assert_equal I18n.t("indexa_capital_items.sync_status.synced", count: 1), @item.sync_status_summary
+ 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