Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
1.8 KB
Raw Blame
module Family::PlaidConnectable
  extend ActiveSupport::Concern

  included do
    has_many :plaid_items, dependent: :destroy
  end

  def can_connect_plaid_us?
    plaid(:us).present?
  end

  # If Plaid provider is configured and user is in the EU region
  def can_connect_plaid_eu?
    plaid(:eu).present? && self.eu?
  end

  # `institution_id` is optional because it only became available to callers once
  # Link's institution metadata was threaded through. Until then the column was
  # populated during the first sync, by PlaidItem#upsert_plaid_institution_snapshot!.
  # Persisting it here closes the window where a freshly linked item is invisible
  # to the duplicate-connection check in PlaidItemsController -- the item most
  # likely to be re-linked by mistake is the one that was just added.
  def create_plaid_item!(public_token:, item_name:, region:, institution_id: nil)
    public_token_response = plaid(region).exchange_public_token(public_token)

    plaid_item = plaid_items.create!(
      name: item_name,
      plaid_id: public_token_response.item_id,
      access_token: public_token_response.access_token,
      plaid_region: region,
      institution_id: institution_id,
      owner: Current.user
    )

    plaid_item.sync_later

    plaid_item
  end

  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(
      user_id: self.id,
      webhooks_url: webhooks_url,
      redirect_url: redirect_url,
      accountable_type: accountable_type,
      access_token: access_token,
      account_selection_enabled: account_selection_enabled
    ).link_token
  end

  private
    def plaid(region)
      Provider::Registry.plaid_provider_for_region(region)
    end
end