Files
sure/app/models/questrade_item/importer.rb
Jestin Palamuttam 5803023fa7 feat(provider): add native Questrade brokerage provider integration (#2534)
* Add native Questrade brokerage provider integration

Adds a per-family Questrade provider so users can sync their Questrade
investment accounts (TFSA, FHSA, RRSP, margin, etc.) directly via
Questrade's free personal API, with no paid aggregator.

- OAuth2 refresh-token flow with single-use token rotation, persisted
  under a row lock. Tokens self-renew on each sync; the connected panel
  lets users paste a fresh token if a connection goes stale (no need to
  disconnect and re-link).
- Imports accounts, balances, positions and activities; multi-currency
  holdings with per-currency cash holdings; Norbert's Gambit journals.
- New-account and link-existing-account flows, settings card with
  desktop-only setup steps, and connect/update/disconnect.
- Restricted to Investment account types. Registered in the provider
  connection-status registry with a syncable scope so it participates in
  nightly family sync.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: linting error

* fix: refresh token encrypted

The OAuth token exchange passed the single-use refresh token as a GET
query parameter, so it could leak into URL-based logs (Sentry
breadcrumbs, APM spans, debug output). Switch to POST with a
form-encoded body (RFC 6749 3.2) so the credential stays out of URLs.
Verified Questrade's token endpoint accepts POST (returns 400 for a bad
token, not 405). Adds a test asserting the token travels in the body.

* Address PR review: authz, data integrity, retries, logging

Batch of fixes from the automated PR review:

- Require admin for all mutating/linking Questrade actions, and gate
  existing-account linking through accessible_accounts + write permission
  (was only Current.family scoped).
- Clear requires_update when a fresh token is accepted; use a real 302
  redirect (not 422) on full-page failures.
- Require refresh_token on all saves (not just create) unless the item is
  scheduled for deletion.
- Migrations target Rails 7.2; questrade_items state columns are NOT NULL.
- Background activity dedup keys on Questrade fields (matches the importer)
  so multiple activities no longer collapse to one.
- Persist the normalized account payload; date-scope synthetic cash
  holdings so daily history is not overwritten.
- Retry 429/5xx via a RetryableResponseError instead of hard-failing.
- Route provider error bodies to DebugLogEntry instead of Rails.logger /
  exception messages, so payloads do not leak into application logs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Address PR review: atomic linking, sync health, retry loop, USD cash

- Wrap account creation + provider linking (+ sync_start_date) in a
  transaction in both link paths so a link failure rolls back the orphan
  account.
- Surface per-account process/schedule failures in the item sync health
  instead of always reporting healthy.
- Always stamp last_activities_sync once the background fetch completes,
  so legitimately empty accounts stop being re-queued every sync.
- Treat only the account-currency (CAD) balance as primary cash; other
  currencies (e.g. USD) now surface as separate cash holdings instead of
  being hidden as primary.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Address PR review: serialize token exchange, real processor tests

- Single-use token race: the SDK now wraps every token exchange (initial
  and 401 re-auth) in a model-supplied lock that reloads and spends the
  freshest persisted token (provided.rb#synchronize_exchange). Two
  concurrent syncs/jobs can no longer double-spend the same refresh token.
  Adds a test asserting the exchange runs inside the lock with the fresh
  token.
- Replace the all-skipped QuestradeAccount processor test stubs with real
  fixture-backed tests covering balance anchoring, holdings import, and
  Buy-trade import (plus blank-symbol / blank-type guards).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Fix indentation of spliced Questrade schema blocks

The manually added questrade_accounts/questrade_items create_table blocks
sat at column 0 instead of the file 2-space indent, so rubocop flagged
them as inconsistent. Re-indent to match the rest of the schema.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Include currency and type in the Questrade activity merge key

Two activities that differ only by currency or type could collapse to a
single row in merge_activities. Add both fields to activity_key in the
importer and the background fetch job so multi-currency imports dedup
correctly.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Address review: infer account currency, Encryptable, safer flag clear

From @jjmata's review:

- Currency: QuestradeAccount#upsert_from_questrade! no longer hardcodes CAD
  for every account. upsert_balances! now infers the home currency from the
  per-currency balances (the currency holding the cash wins, ties broken by
  total equity, default CAD) so USD-denominated accounts are labelled USD and
  match the right combinedBalances anchor. Adds tests for USD and CAD cases.
- QuestradeItem now includes the shared Encryptable concern instead of
  reimplementing encryption_ready? inline.
- QuestradeActivitiesFetchJob#clear_pending_flag is now best-effort so it can
  never mask (and swallow) the original error in perform's rescue.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Fix review issues: safe_return_to_path, DebugLogEntry, financial reset, turbo_prefetch, N+1 counts

- Add safe_return_to_path to QuestradeItemsController (blocks //evil.com
  protocol-relative open redirect; same 3-check guard as PR #2591 Wise provider)
- Pass return_to through select_accounts and complete_account_setup so
  users land back on the account they were linking from
- Replace Rails.logger.error/warn with DebugLogEntry.capture in controller
  and unlinking concern (surface errors in the app debug log UI)
- Add questrade_items to Family::FinancialDataReset::PROVIDER_ITEM_ASSOCIATIONS
  so Reset Financial Data actually removes Questrade data
- Add when "questrade" case to load_provider_items in providers_controller
  so the settings panel lazy-load refresh works
- Fix turbo_prefetch: false on non-lunchflow provider links in
  _method_selector.html.erb and select_provider.html.erb (prevents
  prefetch-cache blank-modal bug for all generic sync providers)
- Preload questrade_accounts: :account_provider and build
  @questrade_account_counts_map in AccountsController; read from map in
  partial instead of calling .count on associations (eliminates N+1)
- Localize default connection name via I18n.t(questrade_items.default_name)
- Add default_name key to questrade_items locale

Patterns and bugs surfaced during review of PR #2591 (Wise provider).

* Cross-apply Wise learnings to Questrade provider

Encryption (matched convention from Wise/jjmata review):
- Add deterministic: true to QuestradeItem#refresh_token
- Add encrypts :raw_payload + :raw_institution_payload to QuestradeItem
- Add Encryptable + encrypts :raw_payload, :raw_holdings_payload,
  :raw_activities_payload, :raw_balances_payload to QuestradeAccount
  (brokerage-specific columns; matches MercuryAccount/UpAccount pattern)

Bug fix:
- Add missing RetryableResponseError class to Provider::Questrade
  (used in with_retries rescue clause but never defined — would cause
  NameError on any rate-limited or 5xx response)

Logging:
- Replace Rails.logger.error with DebugLogEntry.capture in
  QuestradeItem#import_latest_questrade_data, #process_accounts,
  and #schedule_account_syncs to surface errors in the support UI

Consistency:
- Extract update_sync_status(sync, key, **i18n_options) helper in
  QuestradeItem::Syncer, replacing 5 inline sync.update! guard calls
- Use blank? instead of ||= for default name fallback in create action

Tests:
- Add QuestradeItemsControllerTest (18 tests: CRUD, sync, account
  linking/setup flows, admin guard enforcement)
- Add questrade fixtures: questrade_items.yml, questrade_accounts.yml
- Add retry/backoff tests to Provider::QuestradeTest (network error,
  429, 5xx — all verify MAX_RETRIES exhaustion raises Error)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Signed-off-by: Jestin Palamuttam <34907800+jestinjoshi@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 09:00:49 +02:00

292 lines
11 KiB
Ruby

# frozen_string_literal: true
class QuestradeItem::Importer
include SyncStats::Collector
include QuestradeAccount::DataHelpers
# Chunk size for fetching activities
ACTIVITY_CHUNK_DAYS = 365
MAX_ACTIVITY_CHUNKS = 3 # Up to 3 years of history
# Minimum existing activities required before using incremental sync
MINIMUM_HISTORY_FOR_INCREMENTAL = 10
attr_reader :questrade_item, :questrade_provider, :sync
def initialize(questrade_item, questrade_provider:, sync: nil)
@questrade_item = questrade_item
@questrade_provider = questrade_provider
@sync = sync
end
class CredentialsError < StandardError; end
def import
Rails.logger.info "QuestradeItem::Importer - Starting import for item #{questrade_item.id}"
credentials = questrade_item.questrade_credentials
unless credentials
raise CredentialsError, "No Questrade credentials configured for item #{questrade_item.id}"
end
# Step 1: Fetch and store all accounts
import_accounts(credentials)
# Step 2: For LINKED accounts only, fetch data
# Unlinked accounts just need basic info (name, balance) for the setup modal
linked_accounts = QuestradeAccount
.where(questrade_item_id: questrade_item.id)
.joins(:account_provider)
Rails.logger.info "QuestradeItem::Importer - Found #{linked_accounts.count} linked accounts to process"
linked_accounts.each do |questrade_account|
Rails.logger.info "QuestradeItem::Importer - Processing linked account #{questrade_account.id}"
import_account_data(questrade_account, credentials)
end
# Update raw payload on the item
questrade_item.upsert_questrade_snapshot!(stats)
rescue Provider::Questrade::AuthenticationError => e
questrade_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(credentials)
Rails.logger.info "QuestradeItem::Importer - Fetching accounts"
response = questrade_provider.list_accounts
accounts_data = Array(response.is_a?(Hash) ? response[:accounts] : response)
stats["api_requests"] = stats.fetch("api_requests", 0) + 1
stats["total_accounts"] = accounts_data.size
# Track upstream account IDs to detect removed accounts
upstream_account_ids = []
accounts_data.each do |account_data|
begin
account_data = account_data.with_indifferent_access if account_data.is_a?(Hash)
import_account(account_data, credentials)
number = (account_data[:number] || account_data[:id]).to_s
upstream_account_ids << number if number.present?
rescue => e
Rails.logger.error "QuestradeItem::Importer - Failed to import account: #{e.message}"
stats["accounts_skipped"] = stats.fetch("accounts_skipped", 0) + 1
register_error(e, account_data: account_data)
end
end
persist_stats!
# Clean up accounts that no longer exist upstream
prune_removed_accounts(upstream_account_ids)
end
def import_account(account_data, credentials)
questrade_account_id = (account_data[:number] || account_data[:id]).to_s
return if questrade_account_id.blank?
questrade_account = questrade_item.questrade_accounts.find_or_initialize_by(
questrade_account_id: questrade_account_id
)
questrade_account.upsert_from_questrade!(account_data)
stats["accounts_imported"] = stats.fetch("accounts_imported", 0) + 1
end
def import_account_data(questrade_account, credentials)
# Per-currency balances (cash) -> total anchor + cash holdings
store_balances(questrade_account)
# Import holdings
import_holdings(questrade_account, credentials)
# Import activities
import_activities(questrade_account, credentials)
end
# Fetch per-currency balances. Stores primary-currency cash in cash_balance
# (the rest become cash holdings) and the combined total equity used as the
# account's current-balance anchor.
def store_balances(questrade_account)
response = questrade_provider.get_balances(account_id: questrade_account.questrade_account_id)
stats["api_requests"] = stats.fetch("api_requests", 0) + 1
per = Array(response.is_a?(Hash) ? response[:perCurrencyBalances] : nil)
questrade_account.upsert_balances!(per) if per.any?
combined = Array(response.is_a?(Hash) ? response[:combinedBalances] : nil).map { |b| b.with_indifferent_access }
entry = combined.find { |b| b[:currency] == questrade_account.currency } || combined.first
total = entry && (entry[:totalEquity] || entry[:marketValue])
questrade_account.update!(current_balance: total) if total.present?
rescue => e
Rails.logger.warn "QuestradeItem::Importer - Failed to fetch balances for account #{questrade_account.id}: #{e.message}"
end
def import_holdings(questrade_account, credentials)
Rails.logger.info "QuestradeItem::Importer - Fetching holdings for account #{questrade_account.id}"
begin
response = questrade_provider.get_holdings(account_id: questrade_account.questrade_account_id)
holdings_data = Array(response.is_a?(Hash) ? response[:positions] : response)
stats["api_requests"] = stats.fetch("api_requests", 0) + 1
if holdings_data.any?
# Convert SDK objects to hashes for storage
holdings_hashes = holdings_data.map { |h| sdk_object_to_hash(h) }
holdings_hashes = enrich_positions_with_currency(holdings_hashes)
questrade_account.upsert_holdings_snapshot!(holdings_hashes)
stats["holdings_found"] = stats.fetch("holdings_found", 0) + holdings_data.size
end
rescue => e
Rails.logger.warn "QuestradeItem::Importer - Failed to fetch holdings: #{e.message}"
register_error(e, context: "holdings", account_id: questrade_account.id)
end
end
# Questrade positions omit currency. Tag each position with its symbol's
# currency (via /v1/symbols) so USD holdings aren't mislabeled as the
# account's CAD currency.
def enrich_positions_with_currency(positions)
ids = positions.filter_map { |p| p.with_indifferent_access[:symbolId] }.uniq
return positions if ids.empty?
currency_by_id = {}
begin
resp = questrade_provider.get_symbols(ids: ids)
stats["api_requests"] = stats.fetch("api_requests", 0) + 1
Array(resp.is_a?(Hash) ? resp[:symbols] : nil).each do |sym|
sym = sym.with_indifferent_access
currency_by_id[sym[:symbolId]] = sym[:currency]
end
rescue => e
Rails.logger.warn "QuestradeItem::Importer - symbol currency lookup failed: #{e.message}"
return positions
end
positions.map do |p|
p = p.with_indifferent_access
cur = currency_by_id[p[:symbolId]]
p[:currency] = cur if cur.present? && p[:currency].blank?
p
end
end
def import_activities(questrade_account, credentials)
Rails.logger.info "QuestradeItem::Importer - Fetching activities for account #{questrade_account.id}"
begin
# Determine date range
start_date = calculate_start_date(questrade_account)
end_date = Date.current
response = questrade_provider.get_activities(
account_id: questrade_account.questrade_account_id,
start_date: start_date,
end_date: end_date
)
activities_data = Array(response.is_a?(Hash) ? response[:activities] : response)
stats["api_requests"] = stats.fetch("api_requests", 0) + 1
if activities_data.any?
# Convert SDK objects to hashes and merge with existing
activities_hashes = activities_data.map { |a| sdk_object_to_hash(a) }
merged = merge_activities(questrade_account.raw_activities_payload || [], activities_hashes)
questrade_account.upsert_activities_snapshot!(merged)
stats["activities_found"] = stats.fetch("activities_found", 0) + activities_data.size
elsif fresh_linked_account?(questrade_account)
# Fresh account with no activities - schedule background fetch
schedule_background_activities_fetch(questrade_account, start_date)
end
rescue => e
Rails.logger.warn "QuestradeItem::Importer - Failed to fetch activities: #{e.message}"
register_error(e, context: "activities", account_id: questrade_account.id)
end
end
def calculate_start_date(questrade_account)
# Use user-specified start date if available
user_start = questrade_account.sync_start_date
return user_start if user_start.present?
# For accounts with existing history, use incremental sync
existing_count = (questrade_account.raw_activities_payload || []).size
if existing_count >= MINIMUM_HISTORY_FOR_INCREMENTAL && questrade_account.last_activities_sync.present?
# Incremental: go back 30 days from last sync to catch updates
(questrade_account.last_activities_sync - 30.days).to_date
else
# Full sync: go back up to 3 years
(ACTIVITY_CHUNK_DAYS * MAX_ACTIVITY_CHUNKS).days.ago.to_date
end
end
def fresh_linked_account?(questrade_account)
# Account was just linked and has no activity history yet
questrade_account.last_activities_sync.nil? &&
(questrade_account.raw_activities_payload || []).empty?
end
def schedule_background_activities_fetch(questrade_account, start_date)
return if questrade_account.activities_fetch_pending?
Rails.logger.info "QuestradeItem::Importer - Scheduling background activities fetch for account #{questrade_account.id}"
questrade_account.update!(activities_fetch_pending: true)
QuestradeActivitiesFetchJob.perform_later(questrade_account, start_date: start_date)
end
def merge_activities(existing, new_activities)
# Merge by ID, preferring newer data
by_id = {}
existing.each { |a| by_id[activity_key(a)] = a }
new_activities.each { |a| by_id[activity_key(a)] = a }
by_id.values
end
def activity_key(activity)
activity = activity.with_indifferent_access if activity.is_a?(Hash)
# Questrade activities have no id; key on the immutable fields (same basis
# as the processor's synthesized external_id) to dedup across syncs.
[ activity[:transactionDate], activity[:action], activity[:symbolId],
activity[:netAmount], activity[:description], activity[:currency], activity[:type] ].join("-")
end
def prune_removed_accounts(upstream_account_ids)
return if upstream_account_ids.empty?
# Find accounts that exist locally but not upstream
removed = questrade_item.questrade_accounts
.where.not(questrade_account_id: upstream_account_ids)
if removed.any?
Rails.logger.info "QuestradeItem::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