The personal finance app for everyone (by everyone)
Ruby
Link credit card issuers that don’t support Plaid Liabilities (#4547)
Weiqi Zhoued6faa427d0a
diff --git a/app/models/plaid_item/accounts_snapshot.rb b/app/models/plaid_item/accounts_snapshot.rbindex 27f03ad4ce..6a98b12b79 100644--- a/app/models/plaid_item/accounts_snapshot.rb+++ b/app/models/plaid_item/accounts_snapshot.rb@@ -7,8 +7,24 @@ class PlaidItem::AccountsSnapshot@plaid_provider = plaid_providerend+ # Plaid reports no balance at all for some payment-only accounts, such as+ # limited purpose or bill pay accounts that the user can't deselect in Link.+ # PlaidAccount requires a balance and there is nothing to show for them, so+ # new ones are left out instead of failing the whole item import. Accounts+ # already imported stay in: a missing balance there still fails the sync+ # rather than leaving the stored balance and transactions silently stale.def accounts- @accounts ||= plaid_provider.get_item_accounts(plaid_item.access_token).accounts+ @accounts ||= begin+ imported = plaid_item.plaid_accounts.pluck(:plaid_id)++ plaid_provider.get_item_accounts(plaid_item.access_token).accounts.select do |account|+ next true if imported.include?(account.account_id)+ next true if account.balances&.current.present? || account.balances&.available.present?++ log_account_without_balance(account)+ false+ end+ endenddef get_account_data(account_id)@@ -106,7 +122,66 @@ class PlaidItem::AccountsSnapshotenddef liabilities_data+ return @liabilities_data if defined?(@liabilities_data)return nil unless can_fetch_liabilities?- @liabilities_data ||= plaid_provider.get_item_liabilities(plaid_item.access_token)++ @liabilities_data = plaid_provider.get_item_liabilities(plaid_item.access_token)+ rescue Plaid::ApiError => e+ error_code = plaid_error_code(e)+ raise unless liabilities_unavailable?(error_code)++ log_liabilities_unavailable(error_code)+ @liabilities_data = nil+ end++ # Credit card links ask for liabilities as an optional product, and Link+ # records the consent even when Plaid can't add it: the issuer lacks it, or+ # the user withheld the OAuth permission. Consent alone can't gate the call,+ # so skip the data instead of failing the whole sync. Once liabilities was+ # added to the Item (loans, or a card where it worked), errors still raise+ # rather than clearing the liabilities already stored.+ def liabilities_unavailable?(error_code)+ %w[PRODUCTS_NOT_SUPPORTED ACCESS_NOT_GRANTED NO_LIABILITY_ACCOUNTS].include?(error_code) &&+ plaid_item.billed_products.map(&:to_s).exclude?("liabilities")+ end++ def log_account_without_balance(account)+ DebugLogEntry.capture(+ category: "provider_sync",+ level: "info",+ message: "Skipped Plaid account without a balance",+ source: self.class.name,+ provider_key: "plaid",+ family: plaid_item.family,+ metadata: {+ plaid_item_id: plaid_item.id,+ plaid_account_id: account.account_id,+ type: account.type,+ subtype: account.subtype+ }+ )+ end++ def log_liabilities_unavailable(error_code)+ DebugLogEntry.capture(+ category: "provider_sync",+ level: "info",+ message: "Plaid liabilities unavailable for this item",+ source: self.class.name,+ provider_key: "plaid",+ family: plaid_item.family,+ metadata: {+ plaid_item_id: plaid_item.id,+ institution_id: plaid_item.institution_id,+ error_code: error_code+ }+ )+ end++ def plaid_error_code(error)+ body = JSON.parse(error.response_body.to_s)+ body["error_code"] if body.is_a?(Hash)+ rescue JSON::ParserError+ nilendenddiff --git a/app/models/provider/plaid.rb b/app/models/provider/plaid.rbindex 17d5ddc5ab..09d88e18e1 100644--- a/app/models/provider/plaid.rb+++ b/app/models/provider/plaid.rb@@ -58,6 +58,8 @@ class Provider::Plaidelserequest_params[:transactions] = { days_requested: MAX_HISTORY_DAYS }request_params[:products] = [ get_primary_product(accountable_type) ]+ optional = get_optional_products(accountable_type)+ request_params[:optional_products] = optional if optional.any?request_params[:additional_consented_products] = get_additional_consented_products(accountable_type)end@@ -186,26 +188,35 @@ class Provider::Plaidend# The primary Plaid product to request for a given Sure account type.- # Investments map to the `investments` product, liability accounts- # (CreditCard/Loan) to `liabilities`, everything else to `transactions`.+ # Investments map to the `investments` product, loans to `liabilities`,+ # everything else (including credit cards) to `transactions`.def get_primary_product(accountable_type)return "transactions" if eu?case accountable_typewhen "Investment""investments"- when "CreditCard", "Loan"+ when "Loan""liabilities"else"transactions"endend+ # Credit cards ask for `liabilities` (APR, statement balance, minimum+ # payment) on a best-effort basis: an issuer without it, or a failed+ # extraction, still creates the Item with transactions.+ def get_optional_products(accountable_type)+ return [] if eu?++ accountable_type == "CreditCard" ? [ "liabilities" ] : []+ end+# Additional Plaid products to consent to alongside the primary product.#- # We only request the `liabilities` product when the account being linked is- # itself a liability (CreditCard/Loan). Plaid's Link filters out any- # institution that does not support every requested product, so asking for+ # Only liability links request the `liabilities` product: loans as the+ # primary product, credit cards as an optional one. Plaid's Link filters out+ # any institution that does not support every requested product, so asking for# `liabilities` on e.g. an Investment link silently hides investment-only# brokerages like E*TRADE that don't offer it.def get_additional_consented_products(accountable_type)diff --git a/test/models/plaid_item/accounts_snapshot_test.rb b/test/models/plaid_item/accounts_snapshot_test.rbindex d2988d75c8..754512776b 100644--- a/test/models/plaid_item/accounts_snapshot_test.rb+++ b/test/models/plaid_item/accounts_snapshot_test.rb@@ -16,6 +16,52 @@ class PlaidItem::AccountsSnapshotTest < ActiveSupport::TestCase@snapshot.accountsend+ test "leaves out accounts that report no balance" do+ card = OpenStruct.new(+ account_id: "card",+ type: "credit",+ subtype: "credit card",+ balances: OpenStruct.new(current: 120.5, available: nil)+ )+ bill_pay = OpenStruct.new(+ account_id: "bill_pay",+ type: "depository",+ subtype: "checking",+ balances: OpenStruct.new(current: nil, available: nil)+ )+ @plaid_provider.expects(:get_item_accounts).with(@plaid_item.access_token).returns(+ OpenStruct.new(accounts: [ card, bill_pay ])+ ).once++ assert_difference -> { DebugLogEntry.where(source: "PlaidItem::AccountsSnapshot").count }, 1 do+ assert_equal [ "card" ], @snapshot.accounts.map(&:account_id)+ assert_equal [ "card" ], @snapshot.accounts.map(&:account_id)+ end+ end++ test "keeps an already imported account that reports no balance" do+ @plaid_item.plaid_accounts.create!(+ plaid_id: "card",+ name: "Card",+ plaid_type: "credit",+ currency: "USD",+ current_balance: 120.5+ )+ card = OpenStruct.new(+ account_id: "card",+ type: "credit",+ subtype: "credit card",+ balances: OpenStruct.new(current: nil, available: nil)+ )+ @plaid_provider.expects(:get_item_accounts).with(@plaid_item.access_token).returns(+ OpenStruct.new(accounts: [ card ])+ ).once++ assert_no_difference -> { DebugLogEntry.count } do+ assert_equal [ "card" ], @snapshot.accounts.map(&:account_id)+ end+ end+test "fetches transactions data if item supports transactions and any accounts present" do@plaid_item.update!(available_products: [ "transactions" ], billed_products: [])@@ -192,6 +238,98 @@ class PlaidItem::AccountsSnapshotTest < ActiveSupport::TestCase@snapshot.get_account_data("123")end+ test "skips liabilities the institution does not support without failing the sync" do+ # A Credit Card link asks for liabilities as an optional product, and Link+ # records the consent even when the issuer lacks it (e.g. Bilt Rewards).+ @plaid_item.update!(+ available_products: [],+ billed_products: [ "transactions" ],+ raw_payload: { "consented_products" => [ "transactions", "liabilities" ] }+ )++ @snapshot.expects(:accounts).returns([+ OpenStruct.new(account_id: "123", type: "credit", subtype: "credit card"),+ OpenStruct.new(account_id: "456", type: "credit", subtype: "credit card")+ ]).at_least_once++ @plaid_provider.expects(:get_transactions).with(@plaid_item.access_token, next_cursor: nil).returns(+ OpenStruct.new(+ added: [],+ modified: [],+ removed: [],+ cursor: "test_cursor_1"+ )+ ).once+ @plaid_provider.expects(:get_item_investments).never+ @plaid_provider.expects(:get_item_liabilities).with(@plaid_item.access_token).raises(+ Plaid::ApiError.new(code: 400, response_body: { "error_code" => "PRODUCTS_NOT_SUPPORTED" }.to_json)+ ).once++ assert_difference -> { DebugLogEntry.where(source: "PlaidItem::AccountsSnapshot").count }, 1 do+ assert_nil @snapshot.get_account_data("123").liabilities_data+ assert_nil @snapshot.get_account_data("456").liabilities_data+ end+ end++ test "still raises other liabilities errors" do+ @plaid_item.update!(available_products: [], billed_products: [ "liabilities" ])++ @snapshot.expects(:accounts).returns([+ OpenStruct.new(account_id: "123", type: "credit", subtype: "credit card")+ ]).at_least_once++ @plaid_provider.expects(:get_item_liabilities).raises(+ Plaid::ApiError.new(code: 400, response_body: { "error_code" => "ITEM_LOGIN_REQUIRED" }.to_json)+ )++ assert_raises(Plaid::ApiError) { @snapshot.get_account_data("123") }+ end++ test "skips optional liabilities the user did not grant" do+ # With liabilities optional, Plaid still creates the Item when the user+ # withholds the OAuth permission, and /liabilities/get then fails.+ @plaid_item.update!(+ available_products: [],+ billed_products: [ "transactions" ],+ raw_payload: { "consented_products" => [ "transactions", "liabilities" ] }+ )++ %w[ACCESS_NOT_GRANTED NO_LIABILITY_ACCOUNTS].each do |error_code|+ provider = mock+ snapshot = PlaidItem::AccountsSnapshot.new(@plaid_item, plaid_provider: provider)+ snapshot.expects(:accounts).returns([+ OpenStruct.new(account_id: "123", type: "credit", subtype: "credit card")+ ]).at_least_once+ provider.expects(:get_transactions).returns(+ OpenStruct.new(added: [], modified: [], removed: [], cursor: "test_cursor_1")+ )+ provider.expects(:get_item_liabilities).raises(+ Plaid::ApiError.new(code: 400, response_body: { "error_code" => error_code }.to_json)+ ).once++ assert_difference -> { DebugLogEntry.where(source: "PlaidItem::AccountsSnapshot").count }, 1 do+ assert_nil snapshot.get_account_data("123").liabilities_data+ end+ end+ end++ test "still raises unavailable-liabilities errors once liabilities was added to the item" do+ @plaid_item.update!(available_products: [], billed_products: [ "liabilities" ])++ %w[PRODUCTS_NOT_SUPPORTED ACCESS_NOT_GRANTED NO_LIABILITY_ACCOUNTS].each do |error_code|+ provider = mock+ snapshot = PlaidItem::AccountsSnapshot.new(@plaid_item, plaid_provider: provider)+ snapshot.expects(:accounts).returns([+ OpenStruct.new(account_id: "123", type: "loan", subtype: "student")+ ]).at_least_once+ provider.expects(:get_item_liabilities).raises(+ Plaid::ApiError.new(code: 400, response_body: { "error_code" => error_code }.to_json)+ )++ assert_raises(Plaid::ApiError) { snapshot.get_account_data("123") }+ end+ end+test "does not fetch liabilities the institution offers but the user did not consent to" do# A Depository link consents to transactions and investments only. Plaid# still lists liabilities in available_products when the institutiondiff --git a/test/models/provider/plaid_test.rb b/test/models/provider/plaid_test.rbindex 48136723cf..6003753493 100644--- a/test/models/provider/plaid_test.rb+++ b/test/models/provider/plaid_test.rb@@ -52,6 +52,7 @@ class Provider::PlaidTest < ActiveSupport::TestCaserequest = mockPlaid::LinkTokenCreateRequest.expects(:new).with do |params|params[:products] == [ "transactions" ] &&+ params[:optional_products].nil? &¶ms[:additional_consented_products] == [ "investments" ]end.returns(request)@plaid.client.expects(:link_token_create).with(request).returns("response")@@ -64,10 +65,29 @@ class Provider::PlaidTest < ActiveSupport::TestCase)end- test "requests liabilities as primary for a credit card link" do+ test "requests liabilities as an optional product for a credit card link" do+ request = mock+ Plaid::LinkTokenCreateRequest.expects(:new).with do |params|+ params[:products] == [ "transactions" ] &&+ params[:optional_products] == [ "liabilities" ] &&+ params[:required_if_supported_products].nil? &&+ params[:additional_consented_products] == [ "investments" ]+ end.returns(request)+ @plaid.client.expects(:link_token_create).with(request).returns("response")++ @plaid.get_link_token(+ user_id: "test-user-id",+ webhooks_url: "https://example.com/webhooks",+ redirect_url: @redirect_url,+ accountable_type: "CreditCard"+ )+ end++ test "requests liabilities as primary for a loan link" dorequest = mockPlaid::LinkTokenCreateRequest.expects(:new).with do |params|params[:products] == [ "liabilities" ] &&+ params[:optional_products].nil? &¶ms[:additional_consented_products] == [ "transactions", "investments" ]end.returns(request)@plaid.client.expects(:link_token_create).with(request).returns("response")@@ -76,7 +96,7 @@ class Provider::PlaidTest < ActiveSupport::TestCaseuser_id: "test-user-id",webhooks_url: "https://example.com/webhooks",redirect_url: @redirect_url,- accountable_type: "CreditCard"+ accountable_type: "Loan")end