The personal finance app for everyone (by everyone)
Ruby
Plaid: add accounts to an existing connection (#3199)
Tim Katz2fdb9ee175fa
diff --git a/app/controllers/plaid_items_controller.rb b/app/controllers/plaid_items_controller.rbindex 39a0e7226e..47d38282f1 100644--- a/app/controllers/plaid_items_controller.rb+++ b/app/controllers/plaid_items_controller.rb@@ -24,6 +24,7 @@ class PlaidItemsController < ApplicationController@link_token = @plaid_item.get_update_link_token(webhooks_url: webhooks_url,redirect_url: accounts_url,+ account_selection_enabled: @plaid_item.us? && params[:add_accounts] == "true",)rescue Plaid::ApiError => ehandle_link_token_error(e)@@ -45,9 +46,7 @@ class PlaidItemsController < ApplicationControllerenddef sync- unless @plaid_item.syncing?- @plaid_item.sync_later- end+ @plaid_item.sync_later_with_follow_uprespond_to do |format|format.html { redirect_back_or_to accounts_path }diff --git a/app/jobs/plaid_follow_up_sync_job.rb b/app/jobs/plaid_follow_up_sync_job.rbnew file mode 100644index 0000000000..45c9bf1f13--- /dev/null+++ b/app/jobs/plaid_follow_up_sync_job.rb@@ -0,0 +1,33 @@+class PlaidFollowUpSyncJob < ApplicationJob+ queue_as :high_priority++ RETRY_DELAY = 10.seconds+ MAX_ATTEMPTS = 30++ def perform(plaid_item, active_sync_id:, attempts_remaining: MAX_ATTEMPTS)+ if plaid_item.syncs.incomplete.exists?(id: active_sync_id)+ if attempts_remaining.positive?+ self.class.set(wait: RETRY_DELAY).perform_later(+ plaid_item,+ active_sync_id: active_sync_id,+ attempts_remaining: attempts_remaining - 1+ )+ else+ message = "Gave up waiting for PlaidItem #{plaid_item.id} sync #{active_sync_id} to finish"+ DebugLogEntry.capture(+ category: "background_jobs",+ level: "warn",+ message: message,+ source: self.class.name,+ family: plaid_item.family,+ provider_key: "plaid",+ metadata: { plaid_item_id: plaid_item.id, active_sync_id: active_sync_id }+ )+ end++ return+ end++ plaid_item.sync_later+ end+enddiff --git a/app/models/family/plaid_connectable.rb b/app/models/family/plaid_connectable.rbindex b0f1f80d6f..bb37900720 100644--- a/app/models/family/plaid_connectable.rb+++ b/app/models/family/plaid_connectable.rb@@ -29,7 +29,7 @@ module Family::PlaidConnectableplaid_itemend- def get_link_token(webhooks_url:, redirect_url:, accountable_type: nil, region: :us, access_token: nil)+ def get_link_token(webhooks_url:, redirect_url:, accountable_type: nil, region: :us, access_token: nil, account_selection_enabled: false)return nil unless plaid(region)plaid(region).get_link_token(@@ -37,7 +37,8 @@ module Family::PlaidConnectablewebhooks_url: webhooks_url,redirect_url: redirect_url,accountable_type: accountable_type,- access_token: access_token+ access_token: access_token,+ account_selection_enabled: account_selection_enabled).link_tokenenddiff --git a/app/models/plaid_item.rb b/app/models/plaid_item.rbindex c10e987405..f8f3ca16db 100644--- a/app/models/plaid_item.rb+++ b/app/models/plaid_item.rb@@ -36,12 +36,13 @@ class PlaidItem < ApplicationRecord.uniqend- def get_update_link_token(webhooks_url:, redirect_url:)+ def get_update_link_token(webhooks_url:, redirect_url:, account_selection_enabled: false)family.get_link_token(webhooks_url: webhooks_url,redirect_url: redirect_url,region: plaid_region,- access_token: access_token+ access_token: access_token,+ account_selection_enabled: account_selection_enabled)rescue Plaid::ApiError => eerror_body = begin@@ -64,6 +65,17 @@ class PlaidItem < ApplicationRecordendend+ # Queue a fresh import after an in-flight sync. Plaid Link can finish adding+ # accounts after the active sync already fetched its account list.+ def sync_later_with_follow_up+ active_sync = syncs.visible.ordered.first+ sync_later++ return unless active_sync&.reload&.in_progress?++ PlaidFollowUpSyncJob.set(wait: PlaidFollowUpSyncJob::RETRY_DELAY).perform_later(self, active_sync_id: active_sync.id)+ end+def destroy_laterupdate!(scheduled_for_deletion: true)DestroyJob.perform_later(self)diff --git a/app/models/provider/plaid.rb b/app/models/provider/plaid.rbindex d72d540ad3..1e341a26e9 100644--- a/app/models/provider/plaid.rb+++ b/app/models/provider/plaid.rb@@ -42,20 +42,21 @@ class Provider::Plaidraise JWT::VerificationError, "Invalid webhook body hash" unless ActiveSupport::SecurityUtils.secure_compare(expected_hash, actual_hash)end- def get_link_token(user_id:, webhooks_url:, redirect_url:, accountable_type: nil, access_token: nil)+ def get_link_token(user_id:, webhooks_url:, redirect_url:, accountable_type: nil, access_token: nil, account_selection_enabled: false)request_params = {user: { client_user_id: user_id },client_name: "Sure Finances",country_codes: country_codes,language: "en",webhook: webhooks_url,- redirect_uri: redirect_url,- transactions: { days_requested: MAX_HISTORY_DAYS }+ redirect_uri: redirect_url}if access_token.present?request_params[:access_token] = access_token+ request_params[:update] = { account_selection_enabled: true } if account_selection_enabledelse+ request_params[:transactions] = { days_requested: MAX_HISTORY_DAYS }request_params[:products] = [ get_primary_product(accountable_type) ]request_params[:additional_consented_products] = get_additional_consented_products(accountable_type)enddiff --git a/app/views/plaid_items/_plaid_item.html.erb b/app/views/plaid_items/_plaid_item.html.erbindex 36408d89e7..75731c95b6 100644--- a/app/views/plaid_items/_plaid_item.html.erb+++ b/app/views/plaid_items/_plaid_item.html.erb@@ -57,6 +57,14 @@href: edit_plaid_item_path(plaid_item),frame: "modal") %>+ <% elsif plaid_item.us? %>+ <%= render DS::Link.new(+ text: t(".add_accounts"),+ icon: "circle-plus",+ variant: "secondary",+ href: edit_plaid_item_path(plaid_item, add_accounts: true),+ frame: "modal"+ ) %><% elsif Rails.env.development? %><%= icon("refresh-cw",diff --git a/config/locales/views/plaid_items/en.yml b/config/locales/views/plaid_items/en.ymlindex d6fa512f74..d0d07ad148 100644--- a/config/locales/views/plaid_items/en.yml+++ b/config/locales/views/plaid_items/en.yml@@ -10,6 +10,7 @@ en:if the problem persists check the server logs for details.link_token_with_message: "Plaid couldn't open the connection: %{message}"plaid_item:+ add_accounts: Add accountsadd_new: Add new connectionconfirm_accept: Delete institutionconfirm_body: This will permanently delete all the accounts in this group anddiff --git a/test/controllers/plaid_items_controller_test.rb b/test/controllers/plaid_items_controller_test.rbindex 9e171014ec..8f34b653a3 100644--- a/test/controllers/plaid_items_controller_test.rb+++ b/test/controllers/plaid_items_controller_test.rb@@ -58,6 +58,33 @@ class PlaidItemsControllerTest < ActionDispatch::IntegrationTestassert_match(/not enabled for the following products/, flash[:alert])end+ test "edit enables account selection when adding accounts" do+ plaid_item = plaid_items(:one)+ PlaidItem.any_instance.expects(:get_update_link_token).with(+ webhooks_url: webhooks_plaid_url,+ redirect_url: accounts_url,+ account_selection_enabled: true+ ).returns("link-token")++ get edit_plaid_item_url(plaid_item, add_accounts: true)++ assert_response :success+ end++ test "edit does not enable account selection for EU items" do+ plaid_item = plaid_items(:one)+ plaid_item.update!(plaid_region: :eu)+ PlaidItem.any_instance.expects(:get_update_link_token).with(+ webhooks_url: webhooks_plaid_eu_url,+ redirect_url: accounts_url,+ account_selection_enabled: false+ ).returns("link-token")++ get edit_plaid_item_url(plaid_item, add_accounts: true)++ assert_response :success+ end+test "create" do@plaid_provider = mockProvider::Registry.expects(:plaid_provider_for_region).with("us").returns(@plaid_provider)@@ -92,7 +119,7 @@ class PlaidItemsControllerTest < ActionDispatch::IntegrationTesttest "sync" doplaid_item = plaid_items(:one)- PlaidItem.any_instance.expects(:sync_later).once+ PlaidItem.any_instance.expects(:sync_later_with_follow_up).oncepost sync_plaid_item_url(plaid_item)diff --git a/test/jobs/plaid_follow_up_sync_job_test.rb b/test/jobs/plaid_follow_up_sync_job_test.rbnew file mode 100644index 0000000000..52df20fa9d--- /dev/null+++ b/test/jobs/plaid_follow_up_sync_job_test.rb@@ -0,0 +1,50 @@+require "test_helper"++class PlaidFollowUpSyncJobTest < ActiveJob::TestCase+ test "starts a sync after the active sync finishes" do+ plaid_item = plaid_items(:one)+ plaid_item.syncs.destroy_all+ plaid_item.expects(:sync_later).once++ PlaidFollowUpSyncJob.perform_now(plaid_item, active_sync_id: SecureRandom.uuid)+ end++ test "reschedules while a sync is active" do+ plaid_item = plaid_items(:one)+ plaid_item.syncs.destroy_all+ active_sync = plaid_item.syncs.create!+ active_sync.start!++ assert_enqueued_with job: PlaidFollowUpSyncJob do+ PlaidFollowUpSyncJob.perform_now(plaid_item, active_sync_id: active_sync.id, attempts_remaining: 1)+ end+ end++ test "does not overlap an incomplete sync hidden from the UI" do+ plaid_item = plaid_items(:one)+ plaid_item.syncs.destroy_all+ active_sync = plaid_item.syncs.create!(created_at: Sync::VISIBLE_FOR.ago - 1.minute)+ active_sync.start!++ assert_enqueued_with job: PlaidFollowUpSyncJob do+ PlaidFollowUpSyncJob.perform_now(plaid_item, active_sync_id: active_sync.id, attempts_remaining: 1)+ end+ end++ test "captures exhausted retries for support" do+ plaid_item = plaid_items(:one)+ plaid_item.syncs.destroy_all+ active_sync = plaid_item.syncs.create!+ active_sync.start!++ assert_difference "DebugLogEntry.count", 1 do+ PlaidFollowUpSyncJob.perform_now(plaid_item, active_sync_id: active_sync.id, attempts_remaining: 0)+ end++ entry = DebugLogEntry.order(:created_at).last+ assert_equal "background_jobs", entry.category+ assert_equal "PlaidFollowUpSyncJob", entry.source+ assert_equal plaid_item.family, entry.family+ assert_equal active_sync.id, entry.metadata["active_sync_id"]+ end+enddiff --git a/test/models/plaid_item_test.rb b/test/models/plaid_item_test.rbindex 214a5a1dc3..117ec0ad91 100644--- a/test/models/plaid_item_test.rb+++ b/test/models/plaid_item_test.rb@@ -57,6 +57,33 @@ class PlaidItemTest < ActiveSupport::TestCaseassert_predicate @plaid_item.reload, :requires_update?end+ test "get_update_link_token can enable account selection" do+ Family.any_instance.expects(:get_link_token).with(+ webhooks_url: "https://example.com/webhooks",+ redirect_url: "https://example.com/accounts",+ region: @plaid_item.plaid_region,+ access_token: @plaid_item.access_token,+ account_selection_enabled: true+ ).returns("link-token")++ result = @plaid_item.get_update_link_token(+ webhooks_url: "https://example.com/webhooks",+ redirect_url: "https://example.com/accounts",+ account_selection_enabled: true+ )++ assert_equal "link-token", result+ end++ test "sync_later_with_follow_up queues a follow-up after an active sync" do+ active_sync = @plaid_item.syncs.create!+ active_sync.start!++ assert_enqueued_with job: PlaidFollowUpSyncJob do+ @plaid_item.sync_later_with_follow_up+ end+ end+test "get_update_link_token re-raises other Plaid errors so the controller can surface them" do# Issue #1792: silently swallowing all Plaid errors here is what made the# "modal closes with nothing happening" experience so opaque.diff --git a/test/models/provider/plaid_test.rb b/test/models/provider/plaid_test.rbindex 135552e782..83ecd6e9b5 100644--- a/test/models/provider/plaid_test.rb+++ b/test/models/provider/plaid_test.rb@@ -32,6 +32,27 @@ class Provider::PlaidTest < ActiveSupport::TestCaseendend+ test "enables account selection for an update link token" do+ request = mock+ Plaid::LinkTokenCreateRequest.expects(:new).with do |params|+ params[:access_token] == "access-token" &&+ params[:update] == { account_selection_enabled: true } &&+ params[:products].nil? &&+ params[:transactions].nil?+ end.returns(request)+ @plaid.client.expects(:link_token_create).with(request).returns("response")++ result = @plaid.get_link_token(+ user_id: "test-user-id",+ webhooks_url: "https://example.com/webhooks",+ redirect_url: @redirect_url,+ access_token: "access-token",+ account_selection_enabled: true+ )++ assert_equal "response", result+ end+test "exchanges public token" doVCR.use_cassette("plaid/exchange_public_token") dopublic_token = @plaid.create_public_token