Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
1.9 KB
Raw Blame
# frozen_string_literal: true

module QuestradeItem::Unlinking
  # Concern that encapsulates unlinking logic for a Questrade item.
  extend ActiveSupport::Concern

  # Idempotently remove all connections between this Questrade item and local accounts.
  # - Detaches any AccountProvider links for each QuestradeAccount
  # - Detaches Holdings that point at the AccountProvider links
  # Returns a per-account result payload for observability
  def unlink_all!(dry_run: false)
    results = []

    questrade_accounts.find_each do |provider_account|
      links = AccountProvider.where(provider_type: "QuestradeAccount", provider_id: provider_account.id).to_a
      link_ids = links.map(&:id)
      result = {
        provider_account_id: provider_account.id,
        name: provider_account.name,
        provider_link_ids: link_ids
      }
      results << result

      next if dry_run

      begin
        ActiveRecord::Base.transaction do
          # Detach holdings for any provider links found
          if link_ids.any?
            # Bulk-detach: update_all is intentional (no per-row callbacks needed,
            # and it avoids loading every Holding into memory).
            Holding.where(account_provider_id: link_ids).update_all(account_provider_id: nil)
          end

          # Destroy all provider links
          links.each do |ap|
            ap.destroy!
          end
        end
      rescue StandardError => e
        DebugLogEntry.capture(
          category: "provider_sync",
          level: "warn",
          message: "QuestradeItem: failed to fully unlink provider account #\#{provider_account.id}",
          source: self.class.name,
          provider_key: "questrade",
          family: family,
          metadata: { provider_account_id: provider_account.id, link_ids: link_ids, error_class: e.class.name, error_message: e.message }
        )
        result[:error] = e.message
      end
    end

    results
  end
end