The personal finance app for everyone (by everyone)
Ruby
Fix SnapTrade account setup and reconnection (#2858)
Maximus Barbare4c1bc774e5d5
diff --git a/app/controllers/snaptrade_items_controller.rb b/app/controllers/snaptrade_items_controller.rbindex d3d1f3a1e1..b9e5a90138 100644--- a/app/controllers/snaptrade_items_controller.rb+++ b/app/controllers/snaptrade_items_controller.rb@@ -54,7 +54,7 @@ class SnaptradeItemsController < ApplicationControllersnaptrade_item = Current.family.snaptrade_items.find_by(id: params[:item_id])if snaptrade_item- snaptrade_item.sync_later unless snaptrade_item.syncing?+ snaptrade_item.sync_later_with_follow_upif params[:return_to].presence == "setup_accounts"redirect_to setup_accounts_snaptrade_item_path(snaptrade_item, accountable_type: params[:accountable_type].presence), notice: t(".success")@@ -91,6 +91,15 @@ class SnaptradeItemsController < ApplicationController.where(account_providers: { id: nil }).order(:name)+ @account_type_options = [+ [ t(".account_types.depository"), "Depository" ],+ [ t(".account_types.credit_card"), "CreditCard" ],+ [ t(".account_types.investment"), "Investment" ],+ [ t(".account_types.crypto"), "Crypto" ],+ [ t(".account_types.loan"), "Loan" ],+ [ t(".account_types.other_asset"), "OtherAsset" ]+ ]+# Determine view state@syncing = @snaptrade_item.syncing?@waiting_for_sync = no_accounts && @syncing@@ -101,6 +110,7 @@ class SnaptradeItemsController < ApplicationControllerdef complete_account_setupRails.logger.info "SnapTrade complete_account_setup - params: #{params.to_unsafe_h.inspect}"account_ids = params[:account_ids] || []+ account_types = params[:account_types] || {}sync_start_dates = params[:sync_start_dates] || {}Rails.logger.info "SnapTrade complete_account_setup - account_ids: #{account_ids.inspect}, sync_start_dates: #{sync_start_dates.inspect}"@@ -127,7 +137,7 @@ class SnaptradeItemsController < ApplicationControllerendRails.logger.info "SnapTrade complete_account_setup - linking snaptrade_account #{snaptrade_account_id}"- link_snaptrade_account(snaptrade_account)+ link_snaptrade_account(snaptrade_account, account_types[snaptrade_account_id])linked_count += 1Rails.logger.info "SnapTrade complete_account_setup - successfully linked snaptrade_account #{snaptrade_account_id}"rescue => e@@ -233,7 +243,7 @@ class SnaptradeItemsController < ApplicationControllercode_verifier: oauth_session[:code_verifier])- snaptrade_item.sync_later unless snaptrade_item.syncing?+ snaptrade_item.sync_later_with_follow_upif oauth_session[:return_to] == "setup_accounts"redirect_to setup_accounts_snaptrade_item_path(snaptrade_item, accountable_type: oauth_session[:accountable_type].presence), notice: t(".success")@@ -312,7 +322,7 @@ class SnaptradeItemsController < ApplicationControllerendif snaptrade_item.oauth_configured?- snaptrade_item.sync_later unless snaptrade_item.syncing?+ snaptrade_item.sync_later_with_follow_upredirect_to setup_accounts_snaptrade_item_path(snaptrade_item)elseredirect_to oauth_authorize_snaptrade_items_path(item_id: snaptrade_item.id)@@ -370,7 +380,7 @@ class SnaptradeItemsController < ApplicationControllerend# Trigger sync to process the linked account- snaptrade_item.sync_later unless snaptrade_item.syncing?+ snaptrade_item.sync_later_with_follow_upredirect_to account_path(account), notice: t(".success", default: "Successfully linked to SnapTrade account.")rescue => e@@ -425,9 +435,11 @@ class SnaptradeItemsController < ApplicationController{ connections: [] }end- def link_snaptrade_account(snaptrade_account)- # Determine account type based on SnapTrade account type- accountable_type = infer_accountable_type(snaptrade_account.account_type)+ def link_snaptrade_account(snaptrade_account, selected_type)+ accountable_type = selected_type.presence || snaptrade_account.suggested_account_type+ unless Accountable::TYPES.include?(accountable_type)+ raise ArgumentError, "Invalid SnapTrade account type: #{accountable_type}"+ end# Create the Sure accountaccount = Current.family.accounts.create!(@@ -448,20 +460,4 @@ class SnaptradeItemsController < ApplicationControlleraccountend-- def infer_accountable_type(snaptrade_type)- # SnapTrade account types: https://docs.snaptrade.com/reference/get_accounts- case snaptrade_type&.downcase- when "tfsa", "rrsp", "rrif", "resp", "rdsp", "lira", "lrsp", "lif", "rlsp", "prif",- "401k", "403b", "457b", "ira", "roth_ira", "roth_401k", "sep_ira", "simple_ira",- "pension", "retirement", "registered"- "Investment" # Tax-advantaged accounts- when "margin", "cash", "non-registered", "individual", "joint"- "Investment" # Standard brokerage accounts- when "crypto"- "Crypto"- else- "Investment" # Default to Investment for brokerage accounts- end- endenddiff --git a/app/jobs/snaptrade_follow_up_sync_job.rb b/app/jobs/snaptrade_follow_up_sync_job.rbnew file mode 100644index 0000000000..4ab91819a8--- /dev/null+++ b/app/jobs/snaptrade_follow_up_sync_job.rb@@ -0,0 +1,20 @@+class SnaptradeFollowUpSyncJob < ApplicationJob+ queue_as :high_priority++ RETRY_DELAY = 10.seconds+ MAX_ATTEMPTS = 30++ def perform(snaptrade_item, attempts_remaining: MAX_ATTEMPTS)+ if snaptrade_item.syncs.visible.exists?+ if attempts_remaining.positive?+ self.class.set(wait: RETRY_DELAY).perform_later(snaptrade_item, attempts_remaining: attempts_remaining - 1)+ else+ Rails.logger.warn("SnaptradeFollowUpSyncJob - gave up waiting for SnaptradeItem #{snaptrade_item.id} to finish syncing")+ end++ return+ end++ snaptrade_item.sync_later+ end+enddiff --git a/app/models/snaptrade_account.rb b/app/models/snaptrade_account.rbindex 932a72b915..dd3cad25da 100644--- a/app/models/snaptrade_account.rb+++ b/app/models/snaptrade_account.rb@@ -28,6 +28,25 @@ class SnaptradeAccount < ApplicationRecordlinked_accountend+ # SnapTrade normalizes provider-specific account types into three categories.+ # Keep this derived from the raw API payload so existing records immediately+ # receive a sensible setup default without a data migration.+ def suggested_account_type+ payload = raw_payload.to_h.with_indifferent_access+ raw_type = payload[:raw_type].presence || account_type++ case payload[:account_category]+ when "DEPOSIT"+ "Depository"+ when "LOC"+ raw_type.to_s.gsub(/[^a-z]/i, "").downcase.include?("card") ? "CreditCard" : "Loan"+ else+ # SnapTrade documents INVESTMENT and an unknown category as investment+ # accounts. The user may still select a more appropriate Sure type.+ raw_type.to_s.match?(/crypto|bitcoin|ethereum|digital.?asset/i) ? "Crypto" : "Investment"+ end+ end+# Ensure there is an AccountProvider link for this SnapTrade account and the given Account.# Safe and idempotent; returns the AccountProvider or nil if no account is provided.def ensure_account_provider!(account = nil)diff --git a/app/models/snaptrade_item.rb b/app/models/snaptrade_item.rbindex 158b76a50a..7b1094f1a0 100644--- a/app/models/snaptrade_item.rb+++ b/app/models/snaptrade_item.rb@@ -193,9 +193,23 @@ class SnaptradeItem < ApplicationRecord# Override Syncable#syncing? to also show syncing state when activities are being# fetched in the background. This ensures the UI shows the spinner until all data- # is truly imported, not just when the main sync job completes.+ # is truly imported, not just when the main sync job completes. Unlinked+ # provider records are intentionally retained for relinking, so a stale fetch+ # flag on one must not keep the whole connection in a syncing state.def syncing?- super || snaptrade_accounts.where(activities_fetch_pending: true).exists?+ super || linked_snaptrade_accounts.where(activities_fetch_pending: true).exists?+ end++ # Queue a fresh import after an in-flight item sync. This is needed when a+ # user completes OAuth, adds a brokerage, or links an account midway through+ # a sync: Syncable#sync_later intentionally reuses the in-flight Sync.+ def sync_later_with_follow_up+ active_sync = syncs.visible.ordered.first+ sync_later++ return unless active_sync&.reload&.in_progress?++ SnaptradeFollowUpSyncJob.set(wait: SnaptradeFollowUpSyncJob::RETRY_DELAY).perform_later(self)end# Get accounts linked via AccountProviderdiff --git a/app/models/snaptrade_item/syncer.rb b/app/models/snaptrade_item/syncer.rbindex 327f507eea..02118f9e82 100644--- a/app/models/snaptrade_item/syncer.rb+++ b/app/models/snaptrade_item/syncer.rb@@ -45,6 +45,7 @@ class SnaptradeItem::Syncerend# Mark sync health+ snaptrade_item.update!(status: :good) if snaptrade_item.requires_update?collect_health_stats(sync, errors: nil)rescue Provider::Snaptrade::AuthenticationError => esnaptrade_item.update!(status: :requires_update)diff --git a/app/views/snaptrade_items/_snaptrade_item.html.erb b/app/views/snaptrade_items/_snaptrade_item.html.erbindex 35a9dbc741..233b30df5c 100644--- a/app/views/snaptrade_items/_snaptrade_item.html.erb+++ b/app/views/snaptrade_items/_snaptrade_item.html.erb@@ -5,6 +5,7 @@<% snaptrade_registered = snaptrade_item.oauth_configured? %><% brokerage_connect_href = snaptrade_registered ? connect_snaptrade_item_path(snaptrade_item) : oauth_authorize_snaptrade_items_path(item_id: snaptrade_item.id) %><% brokerage_connect_frame = snaptrade_registered ? "_top" : :drawer %>+ <% reconnect_href = oauth_authorize_snaptrade_items_path(item_id: snaptrade_item.id) %><%= render DS::Disclosure.new(variant: :card, open: true) do |disclosure| %><% disclosure.with_summary_content do %>@@ -68,8 +69,8 @@text: t(".reconnect"),icon: "link",variant: "secondary",- href: brokerage_connect_href,- frame: brokerage_connect_frame+ href: reconnect_href,+ frame: "_top") %><% else %><%= icon(diff --git a/app/views/snaptrade_items/setup_accounts.html.erb b/app/views/snaptrade_items/setup_accounts.html.erbindex f736e9686e..aa886315c5 100644--- a/app/views/snaptrade_items/setup_accounts.html.erb+++ b/app/views/snaptrade_items/setup_accounts.html.erb@@ -140,6 +140,13 @@</label></div><div class="mt-3 pl-7" onclick="event.stopPropagation();">+ <%= render DS::Select.new(+ form: form,+ method: "account_types[#{snaptrade_account.id}]",+ items: @account_type_options.map { |label, value| { label: label, value: value } },+ selected: snaptrade_account.suggested_account_type,+ label: t("snaptrade_items.setup_accounts.account_type_label")+ ) %><label for="sync_start_<%= snaptrade_account.id %>" class="block text-xs text-secondary mb-1"><%= t("snaptrade_items.setup_accounts.sync_start_date_label", default: "Import transactions from:") %></label>diff --git a/config/locales/views/snaptrade_items/en.yml b/config/locales/views/snaptrade_items/en.ymlindex b327a85132..2922a53f02 100644--- a/config/locales/views/snaptrade_items/en.yml+++ b/config/locales/views/snaptrade_items/en.yml@@ -73,6 +73,14 @@ en:available_accounts: "Available Accounts"balance_label: "Balance:"account_number: "Account:"+ account_type_label: "Account type"+ account_types:+ depository: "Checking or Savings Account"+ credit_card: "Credit Card"+ investment: "Investment Account"+ crypto: "Crypto Account"+ loan: "Loan or Line of Credit"+ other_asset: "Other Asset"sync_start_date_label: "Import transactions from:"sync_start_date_help: "Leave blank for all available history"create_button: "Create Selected Accounts"diff --git a/test/controllers/snaptrade_items_controller_test.rb b/test/controllers/snaptrade_items_controller_test.rbindex 60dc27c63c..8d64f49791 100644--- a/test/controllers/snaptrade_items_controller_test.rb+++ b/test/controllers/snaptrade_items_controller_test.rb@@ -156,6 +156,49 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTestRails.configuration.x.snaptrade.oauth_client_secret = nilend+ test "oauth_callback clears a reconnect warning after successful authorization" do+ Rails.configuration.x.snaptrade.oauth_client_id = "client-id"+ Rails.configuration.x.snaptrade.oauth_client_secret = "client-secret"+ @snaptrade_item.update!(status: :requires_update)++ get oauth_authorize_snaptrade_items_url(item_id: @snaptrade_item.id)+ oauth_session = session[:snaptrade_oauth]+ Provider::Snaptrade.expects(:exchange_code).returns({ "access_token" => "at", "refresh_token" => "rt" })++ get oauth_callback_snaptrade_items_url(code: "c0de", state: oauth_session["state"])++ assert @snaptrade_item.reload.good?+ ensure+ Rails.configuration.x.snaptrade.oauth_client_id = nil+ Rails.configuration.x.snaptrade.oauth_client_secret = nil+ end++ test "oauth_callback queues a sync even while activities are fetching" do+ Rails.configuration.x.snaptrade.oauth_client_id = "client-id"+ Rails.configuration.x.snaptrade.oauth_client_secret = "client-secret"+ get oauth_authorize_snaptrade_items_url(item_id: @snaptrade_item.id)+ oauth_session = session[:snaptrade_oauth]+ Provider::Snaptrade.expects(:exchange_code).returns({ "access_token" => "at", "refresh_token" => "rt" })+ active_sync = @snaptrade_item.syncs.create!+ active_sync.start!++ assert_enqueued_with job: SnaptradeFollowUpSyncJob do+ get oauth_callback_snaptrade_items_url(code: "c0de", state: oauth_session["state"])+ end+ ensure+ Rails.configuration.x.snaptrade.oauth_client_id = nil+ Rails.configuration.x.snaptrade.oauth_client_secret = nil+ end++ test "Reconnect starts OAuth authorization instead of adding a brokerage" do+ @snaptrade_item.update!(status: :requires_update)++ get accounts_url++ assert_select "a[href='#{oauth_authorize_snaptrade_items_path(item_id: @snaptrade_item.id)}'][data-turbo-frame='_top']", text: /Reconnect/+ assert_select "a[href='#{connect_snaptrade_item_path(@snaptrade_item)}']", text: /Reconnect/, count: 0+ end+test "select_accounts redirects unregistered users into connect flow" dosign_outsign_in @user = users(:empty)@@ -244,6 +287,29 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTestassert_match accounts(:crypto).name, response.bodyend+ test "setup_accounts preselects types from SnapTrade account categories" do+ account = snaptrade_accounts(:fidelity_401k)+ account.update!(raw_payload: { "account_category" => "DEPOSIT" })++ get setup_accounts_snaptrade_item_url(@snaptrade_item)++ assert_select "input[name='account_types[#{account.id}]'][value='Depository']"+ end++ test "complete_account_setup uses the selected account type" do+ account = snaptrade_accounts(:fidelity_401k)+ @snaptrade_item.stubs(:sync_later)++ assert_difference "Account.where(accountable_type: 'Depository').count", 1 do+ post complete_account_setup_snaptrade_item_url(@snaptrade_item), params: {+ account_ids: [ account.id ],+ account_types: { account.id => "Depository" }+ }+ end++ assert_equal "Depository", account.reload.current_account.accountable_type+ end+test "select_existing_account prefers registered active item over pending one" dopending_item = @user.family.snaptrade_items.create!(name: "Pending Registration",diff --git a/test/jobs/snaptrade_follow_up_sync_job_test.rb b/test/jobs/snaptrade_follow_up_sync_job_test.rbnew file mode 100644index 0000000000..5716166daa--- /dev/null+++ b/test/jobs/snaptrade_follow_up_sync_job_test.rb@@ -0,0 +1,23 @@+require "test_helper"++class SnaptradeFollowUpSyncJobTest < ActiveJob::TestCase+ test "queues a sync after the active sync has finished" do+ item = snaptrade_items(:configured_item)++ assert_difference "item.syncs.count", 1 do+ SnaptradeFollowUpSyncJob.perform_now(item)+ end+ end++ test "retries while an item sync is in progress" do+ item = snaptrade_items(:configured_item)+ active_sync = item.syncs.create!+ active_sync.start!++ assert_no_difference "item.syncs.count" do+ assert_enqueued_with job: SnaptradeFollowUpSyncJob do+ SnaptradeFollowUpSyncJob.perform_now(item)+ end+ end+ end+enddiff --git a/test/models/snaptrade_account_test.rb b/test/models/snaptrade_account_test.rbindex 68172bde3f..a6293da6ed 100644--- a/test/models/snaptrade_account_test.rb+++ b/test/models/snaptrade_account_test.rb@@ -74,6 +74,28 @@ class SnaptradeAccountTest < ActiveSupport::TestCaseendend+ test "suggested_account_type maps SnapTrade account categories" do+ account = SnaptradeAccount.new(snaptrade_item: @item_a, name: "Account", currency: "USD")++ account.raw_payload = { "account_category" => "DEPOSIT" }+ assert_equal "Depository", account.suggested_account_type++ account.raw_payload = { "account_category" => "LOC", "raw_type" => "line_of_credit" }+ assert_equal "Loan", account.suggested_account_type++ account.raw_payload = { "account_category" => "LOC", "raw_type" => "CREDIT_CARD" }+ assert_equal "CreditCard", account.suggested_account_type++ account.raw_payload = { "account_category" => "INVESTMENT" }+ assert_equal "Investment", account.suggested_account_type++ account.raw_payload = { "account_category" => "INVESTMENT", "raw_type" => "CRYPTOCURRENCY" }+ assert_equal "Crypto", account.suggested_account_type++ account.raw_payload = {}+ assert_equal "Investment", account.suggested_account_type+ end+# Regression: the after_destroy callback enqueues SnaptradeConnectionCleanupJob,# which references the account/item by id. If it is enqueued before the destroy# transaction commits (Rails 8.1's immediate-enqueue default), a worker can rundiff --git a/test/models/snaptrade_item_test.rb b/test/models/snaptrade_item_test.rbindex fcb6bea4f7..8bdaf3a4f5 100644--- a/test/models/snaptrade_item_test.rb+++ b/test/models/snaptrade_item_test.rb@@ -1,6 +1,8 @@require "test_helper"class SnaptradeItemTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper+setup do@family = families(:dylan_family)end@@ -40,4 +42,23 @@ class SnaptradeItemTest < ActiveSupport::TestCaseassert_equal item.oauth_configured?, item.credentials_configured?assert item.credentials_configured?end++ test "an unlinked account awaiting activities does not keep the item syncing" do+ item = snaptrade_items(:configured_item)+ account = snaptrade_accounts(:fidelity_401k)+ account.update!(activities_fetch_pending: true)++ assert_nil account.current_account+ assert_not item.syncing?+ end++ test "sync_later_with_follow_up queues a follow-up after an active sync" do+ item = snaptrade_items(:configured_item)+ active_sync = item.syncs.create!+ active_sync.start!++ assert_enqueued_with job: SnaptradeFollowUpSyncJob do+ item.sync_later_with_follow_up+ end+ endend