Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(plaid): hold the exchange when re-linking a connected institution (#3658)

Connor McCurdyaf29912ef0cf
diff --git a/app/controllers/plaid_items_controller.rb b/app/controllers/plaid_items_controller.rb
index 043d8d05f0..e2214af8dc 100644
--- a/app/controllers/plaid_items_controller.rb
+++ b/app/controllers/plaid_items_controller.rb
@@ -8,7 +8,7 @@ class PlaidItemsController < ApplicationController
before_action :require_connector_manage!, only: %i[edit destroy sync]
def new
- region = params[:region] == "eu" ? :eu : :us
+ region = normalized_region(params[:region])
webhooks_url = region == :eu ? plaid_eu_webhooks_url : plaid_us_webhooks_url
@link_token = Current.family.get_link_token(
@@ -33,14 +33,41 @@ class PlaidItemsController < ApplicationController
handle_link_token_error(e)
end
+ # Plaid Link on the web holds back every event but OPEN and LAYER_* until the end of
+ # the flow, delivering them alongside onSuccess, so the browser never gets a chance
+ # to step in before the user authenticates. This is the last point where a duplicate
+ # connection can still be stopped: the Item exists at Plaid once Link issues the
+ # public token, but an access token -- what counts against a Trial plan's Item
+ # limit, which /item/remove never gives back -- only exists once we exchange it.
+ # Plaid's duplicate-Items guidance is exactly this: compare the onSuccess metadata
+ # with the user's existing Items, and do not exchange a duplicate.
def create
+ unless params[:confirm_duplicate] == "1"
+ duplicate_items = matching_plaid_items(
+ normalized_region(plaid_item_params[:region]),
+ institution_id: institution_id,
+ institution_name: item_name
+ )
+
+ return render_duplicate_warning(duplicate_items) if duplicate_items.any?
+ end
+
Current.family.create_plaid_item!(
public_token: plaid_item_params[:public_token],
item_name: item_name,
- region: plaid_item_params[:region]
+ region: plaid_item_params[:region],
+ institution_id: institution_id
)
- redirect_to accounts_path, notice: t(".success")
+ # A stream for the JavaScript's fetch rather than a plain redirect: fetch follows
+ # a redirect by itself, and that discarded GET would consume the flash before the
+ # page navigates.
+ respond_to do |format|
+ format.html { redirect_to accounts_path, notice: t(".success") }
+ format.turbo_stream { stream_redirect_to(accounts_path, notice: t(".success")) }
+ end
+ rescue Plaid::ApiError => e
+ handle_exchange_error(e)
end
def destroy
@@ -125,6 +152,120 @@ class PlaidItemsController < ApplicationController
plaid_item_params.dig(:metadata, :institution, :name)
end
+ # Link's `onSuccess` metadata nests the institution, so the id is at
+ # `metadata.institution.institution_id`. `presence` because the duplicate
+ # warning's form sends the id back through a hidden field, which turns a missing
+ # id into an empty string -- and an empty string is not an id to store.
+ def institution_id
+ plaid_item_params.dig(:metadata, :institution, :institution_id).presence
+ end
+
+ # Anything but an explicit "eu" is the US region, the same default the Link opener
+ # falls back to. Reading the value raw would query `plaid_region IS NULL` whenever
+ # a caller omits it, and the duplicate lookup would silently match nothing.
+ def normalized_region(value)
+ value == "eu" ? :eu : :us
+ end
+
+ # Mirrors `select_existing_account`: admins keep oversight of every connection in
+ # the family, a member sees only their own. PlaidItem declares
+ # `credential_scope :per_connection` precisely because a member connecting their
+ # own bank exposes nothing of anyone else's -- warning them about a housemate's
+ # connection would invert that, and would be a false positive besides, since two
+ # people linking their own logins at one bank hold two legitimate Items.
+ def connected_plaid_items(region)
+ scope = Current.family.plaid_items.active.where(plaid_region: region)
+ scope = scope.owned_by(Current.user) unless Current.user.admin?
+ scope.ordered
+ end
+
+ # Matches on institution_id when both sides have one, and otherwise on the
+ # institution name: for items whose first sync never landed and so carry no
+ # institution_id yet -- a broken connection is exactly what a user tries to
+ # re-link -- and for Link metadata that leaves the id out. Only two known ids
+ # that differ rule the name out; then a shared display name is a false positive
+ # rather than a match.
+ #
+ # `plaid_items.name` is written once at create from Link's institution metadata and
+ # never overwritten (there is no update route, and upsert_plaid_institution_snapshot!
+ # does not assign it), so it stays comparable to the institution name that Link's
+ # onSuccess metadata reports.
+ def matching_plaid_items(region, institution_id:, institution_name:)
+ name = normalized_institution_name(institution_name)
+
+ connected_plaid_items(region).includes(:plaid_accounts).select do |item|
+ if institution_id.present? && item.institution_id.present?
+ item.institution_id == institution_id
+ else
+ name.present? && normalized_institution_name(item.name) == name
+ end
+ end
+ end
+
+ def normalized_institution_name(value)
+ value.to_s.strip.downcase.presence
+ end
+
+ # A stream that swaps the Link opener in the modal frame for the warning. The
+ # public token rides along in the warning's "Confirm this connection" form,
+ # because nothing is exchanged unless the user asks for the connection after all.
+ # A page can't render that stream, so a request that wants HTML goes back to
+ # Accounts with the reason instead, and its token is never exchanged.
+ def render_duplicate_warning(duplicate_items)
+ respond_to do |format|
+ format.html { redirect_to accounts_path, alert: t("plaid_items.create.already_connected") }
+ format.turbo_stream do
+ render turbo_stream: turbo_stream.replace(
+ "modal",
+ partial: "plaid_items/duplicate_warning",
+ locals: {
+ duplicate_items: duplicate_items,
+ account_overlap: PlaidItem::AccountOverlap.new(
+ link_accounts: plaid_item_params.dig(:metadata, :accounts),
+ plaid_items: duplicate_items
+ ),
+ public_token: plaid_item_params[:public_token],
+ region: normalized_region(plaid_item_params[:region]).to_s,
+ institution_name: item_name,
+ institution_id: institution_id
+ }
+ )
+ end
+ end
+ end
+
+ # A held public token can expire while the duplicate warning sits open -- Plaid
+ # gives it 30 minutes -- and Plaid reports an expired token and an already
+ # exchanged one alike, as INVALID_PUBLIC_TOKEN. Either way the user has to go
+ # through Link again, so say that instead of failing with an error page.
+ def handle_exchange_error(error)
+ error_body = safe_parse_plaid_error(error)
+ error_code = error_body["error_code"].to_s
+ token_expired = error_code == "INVALID_PUBLIC_TOKEN"
+
+ DebugLogEntry.capture(
+ category: "provider_auth",
+ level: token_expired ? "warn" : "error",
+ message: "Plaid public token exchange failed: #{error_code.presence || error.class.name}",
+ source: "PlaidItemsController#create",
+ provider_key: "plaid",
+ family: Current.family,
+ user: Current.user,
+ metadata: {
+ error_code: error_code.presence,
+ request_id: error_body["request_id"],
+ region: plaid_item_params[:region]
+ }
+ )
+
+ alert = token_expired ? t("plaid_items.create.token_expired") : t("plaid_items.create.exchange_failed")
+
+ respond_to do |format|
+ format.html { redirect_to accounts_path, alert: alert }
+ format.turbo_stream { stream_redirect_to(accounts_path, alert: alert) }
+ end
+ end
+
# When `link_token/create` (or the update equivalent) raises, surface a
# friendly alert to the user instead of letting the modal frame render
# blank. Plaid configuration/product-access errors are the common case for
diff --git a/app/javascript/controllers/plaid_controller.js b/app/javascript/controllers/plaid_controller.js
index 735c6f4200..bf8689e85c 100644
--- a/app/javascript/controllers/plaid_controller.js
+++ b/app/javascript/controllers/plaid_controller.js
@@ -2,6 +2,7 @@ import { Controller } from "@hotwired/stimulus";
// Connects to data-controller="plaid"
export default class extends Controller {
+ static targets = ["createFailed"];
static values = {
linkToken: String,
region: { type: String, default: "us" },
@@ -106,10 +107,13 @@ export default class extends Controller {
return;
}
- // For new connections, create a new Plaid item
+ // For new connections, create a new Plaid item. The server answers with a
+ // Turbo Stream: a redirect once the item exists, or -- when the institution is
+ // already connected -- a warning for the modal frame, with the exchange held.
fetch("/plaid_items", {
method: "POST",
headers: {
+ Accept: "text/vnd.turbo-stream.html, text/html",
"Content-Type": "application/json",
"X-CSRF-Token": document.querySelector('[name="csrf-token"]').content,
},
@@ -120,13 +124,39 @@ export default class extends Controller {
region: this.regionValue,
},
}),
- }).then((response) => {
- if (response.redirected) {
- window.location.href = response.url;
- }
- });
+ })
+ .then(async (response) => {
+ if (response.redirected) {
+ window.location.href = response.url;
+ return;
+ }
+
+ // Checked first, because renderStreamMessage appends whatever it is given to
+ // the page.
+ const contentType = response.headers.get("Content-Type") || "";
+ if (response.ok && contentType.includes("text/vnd.turbo-stream.html")) {
+ Turbo.renderStreamMessage(await response.text());
+ return;
+ }
+
+ this.showCreateFailed(`Unexpected response: ${response.status}`);
+ })
+ .catch((error) => this.showCreateFailed(error));
};
+ // Link has closed by now, so when the request fails outright -- the network, or a
+ // server error the controller doesn't answer with a stream -- nothing else on the
+ // page says so. Whether the connection was added is unknown, so the alert, rendered
+ // by the server into a template, asks the user to check.
+ showCreateFailed(error) {
+ console.error("Failed to add the Plaid connection", error);
+
+ const tray = document.getElementById("notification-tray");
+ if (!tray || !this.hasCreateFailedTarget) return;
+
+ tray.append(this.createFailedTarget.content.cloneNode(true));
+ }
+
handleExit = (err, metadata) => {
// If there was an error during update mode, refresh the page to show
// latest status. Guard `metadata` (Plaid can fire onExit with it
diff --git a/app/models/family/plaid_connectable.rb b/app/models/family/plaid_connectable.rb
index 4512d30629..683ceccce5 100644
--- a/app/models/family/plaid_connectable.rb
+++ b/app/models/family/plaid_connectable.rb
@@ -14,7 +14,13 @@ module Family::PlaidConnectable
plaid(:eu).present? && self.eu?
end
- def create_plaid_item!(public_token:, item_name:, region:)
+ # `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!(
@@ -22,6 +28,7 @@ module Family::PlaidConnectable
plaid_id: public_token_response.item_id,
access_token: public_token_response.access_token,
plaid_region: region,
+ institution_id: institution_id,
owner: Current.user
)
diff --git a/app/models/plaid_item/account_overlap.rb b/app/models/plaid_item/account_overlap.rb
new file mode 100644
index 0000000000..9854e5d3c4
--- /dev/null
+++ b/app/models/plaid_item/account_overlap.rb
@@ -0,0 +1,71 @@
+# Compares the accounts Plaid Link reported for a new connection with the accounts of
+# the connections a user already holds at that institution, so the duplicate warning
+# can say what the new connection would duplicate instead of asking which login the
+# user signed in with -- a returning user comes through Plaid's phone-number flow
+# with no bank login, and Link may preselect every account or skip account selection
+# altogether.
+#
+# Plaid's duplicate-Items guidance is to compare institution, account name and mask.
+# The institution has already matched by the time this runs, so it compares name and
+# mask: Plaid issues new account ids for every Item, so ids never match across them.
+class PlaidItem::AccountOverlap
+ attr_reader :link_accounts
+
+ # `link_accounts` is the `accounts` array from Link's onSuccess metadata, each with
+ # a "name" and a "mask". `plaid_items` are the existing connections the duplicate
+ # check matched.
+ def initialize(link_accounts:, plaid_items:)
+ @link_accounts = Array(link_accounts).map { |account| account.to_h.stringify_keys.slice("name", "mask") }
+ @plaid_items = plaid_items
+ end
+
+ # :all_connected, :some_connected or :none_connected -- or :unknown when the
+ # comparison can't be trusted:
+ # - Link reported no accounts.
+ # - A reported account has no mask. Brokerages and crypto exchanges often report
+ # none, with generic names such as "Brokerage", so a different login's accounts
+ # can match on name alone -- and an :all_connected verdict hides the dialog's
+ # override.
+ # - A matching connection has no accounts on record yet because its first sync
+ # never landed, so any account Link reported might be one of its accounts.
+ def state
+ return :unknown if link_accounts.empty? || link_accounts.any? { |account| account["mask"].blank? }
+ return :unknown if plaid_items.any? { |item| item.plaid_accounts.empty? }
+ return :all_connected if unconnected_accounts.empty?
+
+ unconnected_accounts.size == link_accounts.size ? :none_connected : :some_connected
+ end
+
+ def unconnected_accounts
+ @unconnected_accounts ||= link_accounts.reject { |account| connected_keys.include?(key_for(account["name"], account["mask"])) }
+ end
+
+ def connected_count
+ link_accounts.size - unconnected_accounts.size
+ end
+
+ # The connections holding at least one reported account -- the ones this link
+ # actually overlaps. A family can hold several connections at one institution, often
+ # for different logins, and the others have nothing to do with this one. Empty when
+ # nothing matches.
+ def matching_items
+ @matching_items ||= plaid_items.select do |item|
+ item.plaid_accounts.any? { |account| link_keys.include?(key_for(account.name, account.mask)) }
+ end
+ end
+
+ private
+ attr_reader :plaid_items
+
+ def link_keys
+ @link_keys ||= link_accounts.to_set { |account| key_for(account["name"], account["mask"]) }
+ end
+
+ def connected_keys
+ @connected_keys ||= plaid_items.flat_map(&:plaid_accounts).to_set { |account| key_for(account.name, account.mask) }
+ end
+
+ def key_for(name, mask)
+ [ name.to_s.strip.downcase, mask.to_s.strip ]
+ end
+end
diff --git a/app/views/plaid_items/_auto_link_opener.html.erb b/app/views/plaid_items/_auto_link_opener.html.erb
index 7e9c769503..65d4074888 100644
--- a/app/views/plaid_items/_auto_link_opener.html.erb
+++ b/app/views/plaid_items/_auto_link_opener.html.erb
@@ -6,4 +6,11 @@
plaid_region_value: region,
plaid_item_id_value: item_id,
plaid_is_update_value: is_update
- } %>
+ } do %>
+ <%# The alert the controller shows if the request that adds a connection fails
+ outright, rendered here because the controller can't render a partial. A
+ template stays inert until then. %>
+ <template data-plaid-target="createFailed">
+ <%= render "shared/notifications/alert", message: t(".create_failed") %>
+ </template>
+<% end %>
diff --git a/app/views/plaid_items/_duplicate_warning.html.erb b/app/views/plaid_items/_duplicate_warning.html.erb
new file mode 100644
index 0000000000..8ef25be341
--- /dev/null
+++ b/app/views/plaid_items/_duplicate_warning.html.erb
@@ -0,0 +1,231 @@
+<%# locals: (duplicate_items:, account_overlap:, public_token:, region:, institution_name:, institution_id:) %>
+
+<%# Rendered by PlaidItemsController#create in place of exchanging the public token:
+ the user has finished Link, but nothing has been added. When the dialog offers
+ "Confirm this connection", the token waits in that form, and is spent only if the
+ user submits it. %>
+
+<% state = account_overlap.state %>
+
+<%# The connections to show. When accounts match, only those holding them: a second
+ login's connection at the same institution has nothing to do with this link, and
+ listing it would make "this connection" ambiguous and could put an update action
+ on the wrong one. When nothing matches, or nothing can be compared, every
+ connection at the institution stays listed as context. %>
+<% listed_items = state.in?(%i[all_connected some_connected]) ? account_overlap.matching_items : duplicate_items %>
+<% masked = ->(mask) { t(".mask", mask: mask) if mask.present? } %>
+
+<%# Connections this user can take into update mode: US ones they may manage, and that
+ are theirs. An admin may manage a member's connection, but update mode signs in
+ with that connection's bank login, which is the member's -- so only the user's own
+ connections count, along with those predating per-user ownership, which have no
+ owner and which admins have always managed.
+
+ Updating is offered only where it fits -- when some accounts are new, or when
+ there is nothing to compare, often because a connection's first sync never
+ landed. With exactly one such connection, its button joins the actions at the
+ bottom. With several, each card keeps its own, since one button could not say
+ which connection it updates. %>
+<% users_own = ->(item) { item.owned_by?(Current.user) || item.owner_id.nil? } %>
+<% updatable_items = listed_items.select { |item| item.us? && item.manageable_by?(Current.user) && users_own.call(item) } %>
+
+<%# When every account matches only other members' connections, the user didn't make
+ "this connection": their own login reaches the same accounts -- joint accounts,
+ say -- so the warning says whose connection already has them instead. %>
+<% others_connected = state == :all_connected && listed_items.none?(&users_own) %>
+<% offers_update = state.in?(%i[some_connected unknown]) %>
+<% bottom_update_item = updatable_items.first if offers_update && updatable_items.one? %>
+<% card_update_items = offers_update && updatable_items.many? ? updatable_items : [] %>
+
+<%# Close discards the held token without exchanging it. %>
+<% close_button = ->(variant) do
+ render DS::Button.new(
+ text: t(".close"),
+ variant: variant,
+ size: :sm,
+ full_width: true,
+ data: { action: "DS--dialog#close" }
+ )
+ end %>
+
+<%# Sends the held public token back to create, with confirm_duplicate to let it past
+ the check. The token already passed through the browser on its way from Link, is
+ single-use, expires after 30 minutes, and is worthless without the server's Plaid
+ secret, so a hidden field exposes nothing new. _top because a confirmed create
+ redirects to Accounts, which has no modal frame to fill. %>
+<% confirm_button = ->(variant) do
+ render DS::Button.new(
+ text: t(".confirm"),
+ href: plaid_items_path,
+ method: :post,
+ params: {
+ confirm_duplicate: "1",
+ plaid_item: {
+ public_token: public_token,
+ region: region,
+ metadata: { institution: { name: institution_name, institution_id: institution_id } }
+ }
+ },
+ variant: variant,
+ size: :sm,
+ full_width: true,
+ frame: "_top"
+ )
+ end %>
+
+<%= turbo_frame_tag "modal" do %>
+ <%# disable_click_outside: whether to duplicate a connection or keep the existing one
+ is not a decision a stray click should make, and this dialog opens as Link
+ closes, wherever Link left the pointer. The header close button and Esc still
+ dismiss it.
+
+ turbo_temporary: the dialog carries a live public token, and Turbo would
+ otherwise keep it in the page snapshot it caches on navigation -- so Back would
+ restore a dialog still able to spend it. %>
+ <%= render DS::Dialog.new(disable_click_outside: true, data: { turbo_temporary: true }) do |dialog| %>
+ <%# A family can legitimately hold several connections for one institution -- that is
+ the state this warning exists to stop growing -- so the title counts them. When
+ every account matches, this is the same connection made twice, and the title
+ says so -- unless the matches are all other members', in which case it is the
+ accounts that are already connected, not this connection. %>
+ <% title = if others_connected
+ t(".title_others_connected", count: account_overlap.link_accounts.size)
+ elsif state == :all_connected
+ t(".title_all_connected")
+ else
+ t(".title", count: listed_items.size)
+ end %>
+ <% dialog.with_header(title: title) %>
+
+ <% dialog.with_body do %>
+ <div class="space-y-4">
+ <%# What the new connection would duplicate, from the accounts Link just reported,
+ so the consequences are stated only where they hold. A second login with
+ different accounts duplicates nothing, and a warning that is false for the
+ people the override serves costs more than one that is merely unneeded. %>
+ <div class="space-y-2">
+ <% if others_connected %>
+ <% other_owners = listed_items.filter_map(&:owner).uniq %>
+ <% if other_owners.one? %>
+ <p class="text-sm text-secondary"><%= t(".overlap.others_connected", count: account_overlap.link_accounts.size, name: other_owners.first.display_name) %></p>
+ <% else %>
+ <p class="text-sm text-secondary"><%= t(".overlap.others_connected_several", count: account_overlap.link_accounts.size) %></p>
+ <% end %>
+ <% elsif state == :all_connected %>
+ <p class="text-sm text-secondary"><%= t(".overlap.all_connected", count: account_overlap.link_accounts.size) %></p>
+ <%# Close is the only action here, so say where the other reasons to re-link
+ go: Add accounts on the existing connection, where Plaid supports it, or
+ New account again with the other login. Link can report an institution
+ id without a name, and the matched connection carries the same
+ institution's name. %>
+ <% institution = institution_name.presence || listed_items.first.name %>
+ <% if updatable_items.any? %>
+ <p class="text-sm text-secondary"><%= t(".overlap.more_accounts", institution: institution) %></p>
+ <% end %>
+ <p class="text-sm text-secondary"><%= t(".overlap.different_login", institution: institution) %></p>
+ <% elsif state == :some_connected %>
+ <p class="text-sm text-secondary"><%= t(".overlap.some_connected.unconnected", count: account_overlap.unconnected_accounts.size) %></p>
+ <dl class="space-y-1">
+ <% account_overlap.unconnected_accounts.each do |account| %>
+ <%= render DS::DetailRow.new(label: account["name"], value: masked.call(account["mask"]), align: :baseline) %>
+ <% end %>
+ </dl>
+ <p class="text-sm text-secondary"><%= t(".overlap.some_connected.connected", count: account_overlap.connected_count) %></p>
+ <% elsif state == :none_connected %>
+ <p class="text-sm text-secondary"><%= t(".overlap.none_connected") %></p>
+ <% else %>
+ <p class="text-sm text-secondary"><%= t(".overlap.unknown", count: listed_items.size) %></p>
+ <% end %>
+ </div>
+
+ <div class="space-y-3">
+ <% listed_items.each do |plaid_item| %>
+ <div class="p-3 border border-primary rounded-lg space-y-3">
+ <div class="flex items-baseline justify-between gap-2">
+ <span class="font-medium text-sm text-primary"><%= plaid_item.name %></span>
+ <span class="text-xs text-secondary whitespace-nowrap">
+ <%= t(".linked_on", date: l(plaid_item.created_at.to_date, format: :short_with_year)) %>
+ </span>
+ </div>
+
+ <%# owner_id is nullable -- connections predating per-user ownership (#3613)
+ carry none, and owned_by? is false for those, so attribute only when
+ there is someone to name. %>
+ <% if plaid_item.owner.present? && !plaid_item.owned_by?(Current.user) %>
+ <p class="text-xs text-secondary">
+ <%= t(".connected_by", name: plaid_item.owner.display_name) %>
+ </p>
+ <% end %>
+
+ <%# plaid_accounts, not accounts: PlaidItem#accounts resolves through the
+ linked Account and returns nothing for a connection whose accounts were
+ never linked -- which is exactly the broken connection a user re-links. %>
+ <% if plaid_item.plaid_accounts.any? %>
+ <dl class="space-y-1">
+ <% plaid_item.plaid_accounts.each do |plaid_account| %>
+ <%= render DS::DetailRow.new(label: plaid_account.name, value: masked.call(plaid_account.mask), align: :baseline) %>
+ <% end %>
+ </dl>
+ <% else %>
+ <p class="text-xs text-secondary"><%= t(".no_accounts") %></p>
+ <% end %>
+
+ <% if card_update_items.include?(plaid_item) %>
+ <%= render "plaid_items/update_connection_link", plaid_item: plaid_item %>
+ <% elsif plaid_item.manageable_by?(Current.user) && !plaid_item.us? %>
+ <%# Plaid does not support update-mode account selection for UK/EU
+ institutions and directs callers to remove the Item and create a
+ new one instead, so there is no update path to offer here. Say why,
+ rather than silently dropping the action. %>
+ <p class="text-xs text-secondary"><%= t(".eu_no_add_accounts") %></p>
+ <%= render DS::Link.new(
+ text: t(".manage_connection"),
+ href: accounts_path,
+ variant: :outline,
+ size: :sm,
+ full_width: true,
+ data: { turbo_frame: "_top" }
+ ) %>
+ <% end %>
+ </div>
+ <% end %>
+ </div>
+
+ <%# Each case leads with what its evidence suggests:
+ - Every account already connected: Close alone. Adding could only duplicate
+ them. When the connection is the user's own, the text above says where
+ else to go.
+ - Some new: update the existing connection, which adds them without a second
+ connection. Confirming stays last, for a different login that shares an
+ account, such as a joint account. When the overlap is only with other
+ members' connections, it is that different login, so confirming leads.
+ - None connected: confirm, since this is likely a different login.
+ - Nothing to compare: Close, since neither updating nor confirming is
+ clearly right. %>
+ <div class="space-y-2">
+ <% if state == :all_connected %>
+ <%= close_button.call(:primary) %>
+ <% elsif state == :some_connected && bottom_update_item.nil? && listed_items.none?(&users_own) %>
+ <%= confirm_button.call(:primary) %>
+ <%= close_button.call(:outline) %>
+ <% elsif state == :some_connected %>
+ <% if bottom_update_item %>
+ <%= render "plaid_items/update_connection_link", plaid_item: bottom_update_item, variant: :primary %>
+ <% end %>
+ <%= close_button.call(bottom_update_item ? :outline : :primary) %>
+ <%= confirm_button.call(:ghost) %>
+ <% elsif state == :none_connected %>
+ <%= confirm_button.call(:primary) %>
+ <%= close_button.call(:outline) %>
+ <% else %>
+ <%= close_button.call(:primary) %>
+ <% if bottom_update_item %>
+ <%= render "plaid_items/update_connection_link", plaid_item: bottom_update_item %>
+ <% end %>
+ <%= confirm_button.call(:outline) %>
+ <% end %>
+ </div>
+ </div>
+ <% end %>
+ <% end %>
+<% end %>
diff --git a/app/views/plaid_items/_update_connection_link.html.erb b/app/views/plaid_items/_update_connection_link.html.erb
new file mode 100644
index 0000000000..362ab46241
--- /dev/null
+++ b/app/views/plaid_items/_update_connection_link.html.erb
@@ -0,0 +1,14 @@
+<%# locals: (plaid_item:, variant: :outline) %>
+
+<%# Opens Plaid's update mode for the existing connection, which is the only way Plaid
+ changes one. turbo_prefetch is off because GET edit mints an update-mode link token
+ as a side effect, so a hover would call /link/token/create. %>
+<%= render DS::Link.new(
+ text: t("plaid_items.duplicate_warning.update_existing"),
+ href: edit_plaid_item_path(plaid_item, add_accounts: true),
+ variant: variant,
+ size: :sm,
+ full_width: true,
+ frame: "modal",
+ data: { turbo_prefetch: "false" }
+ ) %>
diff --git a/config/locales/views/plaid_items/en.yml b/config/locales/views/plaid_items/en.yml
index f7801213f3..dfdd179598 100644
--- a/config/locales/views/plaid_items/en.yml
+++ b/config/locales/views/plaid_items/en.yml
@@ -1,10 +1,76 @@
---
en:
plaid_items:
+ auto_link_opener:
+ create_failed: We couldn't confirm this connection was added. Reload the page to
+ check before trying again.
create:
+ already_connected: You already have a connection for this institution, so this
+ one wasn't added.
+ exchange_failed: We couldn't add this connection. Try again, and if the problem
+ continues, check the server logs.
success: Account linked successfully. Please wait for accounts to sync.
+ token_expired: This connection expired before it was added. Connect the institution
+ again.
destroy:
success: Accounts scheduled for deletion.
+ duplicate_warning:
+ close: Close
+ confirm: Confirm this connection
+ connected_by: Connected by %{name}
+ eu_no_add_accounts: Plaid doesn't support adding accounts to an existing
+ EU connection. To change which accounts are connected, remove this one and
+ add it again.
+ linked_on: Linked %{date}
+ manage_connection: Go to accounts
+ mask: "****%{mask}"
+ no_accounts: No accounts have synced from this connection yet.
+ overlap:
+ all_connected:
+ one: The account you tried to add is already connected, so adding it again
+ would only create a duplicate.
+ other: The %{count} accounts you tried to add are all already connected, so
+ adding them again would only create duplicates.
+ different_login: To connect a different %{institution} login, choose New account
+ again, and sign in with that login through Plaid.
+ more_accounts: To add more accounts to this connection, close this and choose
+ Add accounts on the %{institution} connection.
+ others_connected:
+ one: Sure already has this account through %{name}'s connection, so adding
+ yours would only create a duplicate.
+ other: Sure already has these accounts through %{name}'s connection, so adding
+ yours would only create duplicates.
+ others_connected_several:
+ one: Sure already has this account through other members' connections, so
+ adding yours would only create a duplicate.
+ other: Sure already has these accounts through other members' connections, so
+ adding yours would only create duplicates.
+ none_connected: None of the accounts you tried to add are connected yet, so this
+ is likely a different login. Adding it only counts as another Plaid connection.
+ some_connected:
+ connected:
+ one: The other one is already connected, so adding this connection would
+ duplicate it and count as another Plaid connection.
+ other: The other %{count} are already connected, so adding this connection
+ would duplicate them and count as another Plaid connection.
+ unconnected:
+ one: "One account you tried to add isn't connected yet:"
+ other: "%{count} accounts you tried to add aren't connected yet:"
+ unknown:
+ one: These accounts can't be checked against your existing connection. If
+ they're the same accounts, adding this connection would duplicate them and
+ count as another Plaid connection.
+ other: These accounts can't be checked against your existing connections. If
+ they're the same accounts, adding this connection would duplicate them and
+ count as another Plaid connection.
+ title:
+ one: You already have a connection for this institution
+ other: You already have %{count} connections for this institution
+ title_all_connected: You've already made this connection
+ title_others_connected:
+ one: This account is already connected
+ other: These accounts are already connected
+ update_existing: Update existing connection
errors:
link_token_generic: We couldn't open Plaid right now. Please try again, and
if the problem persists check the server logs for details.
diff --git a/test/controllers/plaid_items_controller_test.rb b/test/controllers/plaid_items_controller_test.rb
index 5b8e022795..e1e0f6450e 100644
--- a/test/controllers/plaid_items_controller_test.rb
+++ b/test/controllers/plaid_items_controller_test.rb
@@ -100,11 +100,15 @@ class PlaidItemsControllerTest < ActionDispatch::IntegrationTest
plaid_item: {
public_token: public_token,
region: "us",
- metadata: { institution: { name: "Plaid Item Name" } }
+ metadata: { institution: { name: "Plaid Item Name", institution_id: "ins_mock" } }
}
}
end
+ # Link's onSuccess metadata nests the institution. Persisting the id here closes
+ # the window where a just-linked connection is invisible to the duplicate check,
+ # which would otherwise last until the first sync completes.
+ assert_equal "ins_mock", PlaidItem.order(:created_at).last.institution_id
assert_equal "Account linked successfully. Please wait for accounts to sync.", flash[:notice]
assert_redirected_to accounts_path
end
@@ -322,4 +326,774 @@ class PlaidItemsControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to account_path(account)
assert_equal "No available Plaid accounts to link. Please connect a new Plaid account first.", flash[:alert]
end
+
+ # --- Duplicate-connection gate ---------------------------------------------
+ #
+ # Plaid Link on the web holds back every event except OPEN and LAYER_* until the
+ # end of the flow and delivers them alongside onSuccess, so nothing in the browser
+ # runs early enough to stop a user from authenticating at a bank they already
+ # connected. What is left is this point, before the public token is exchanged:
+ # an access token is what counts against a Trial plan's Item limit, and Plaid's
+ # duplicate-Items guidance is not to exchange a duplicate at all. The JavaScript
+ # only forwards onSuccess and renders whatever comes back, so these tests carry
+ # the weight.
+
+ HELD_TOKEN = "public-sandbox-held"
+
+ test "create holds the exchange when the institution is already connected" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin))
+ stub_plaid_provider.expects(:exchange_public_token).never
+
+ assert_no_difference "PlaidItem.count" do
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+ end
+
+ assert_duplicate_warning
+ end
+
+ test "create exchanges the held token once the user confirms" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin))
+
+ assert_exchanges do
+ post_link(institution_id: "ins_example", institution_name: "Example Bank", confirm: true)
+ end
+ end
+
+ # A stream rather than a plain redirect, because the JavaScript's fetch follows a
+ # redirect by itself -- and that discarded GET consumed the flash, so the success
+ # notice never reached the page the user actually landed on.
+ test "create redirects by stream with the success notice when nothing matches" do
+ assert_exchanges do
+ post_link(institution_id: "ins_new", institution_name: "New Bank")
+ end
+
+ assert_equal I18n.t("plaid_items.create.success"), flash[:notice]
+ end
+
+ test "create lists the existing connection with its accounts and masks" do
+ create_plaid_item(
+ name: "Example Bank",
+ institution_id: "ins_example",
+ owner: users(:family_admin),
+ accounts: [
+ { name: "Example Checking", mask: "4321" },
+ { name: "Example Savings", mask: "8765" }
+ ]
+ )
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+
+ assert_duplicate_warning
+ assert_match "Example Checking", response.body
+ assert_match "4321", response.body
+ assert_match "Example Savings", response.body
+ assert_match "8765", response.body
+ end
+
+ # A family that already hit this bug holds several connections for one institution,
+ # and is exactly who the warning matters most to. Every match is listed, and the
+ # title counts them rather than reading as though there were one.
+ test "create lists every connection for the institution" do
+ first = create_plaid_item(name: "Example Bank", institution_id: "ins_example",
+ owner: users(:family_admin), accounts: [ { name: "First Checking", mask: "4321" } ])
+ second = create_plaid_item(name: "Example Bank (2nd login)", institution_id: "ins_example",
+ owner: users(:family_admin), accounts: [ { name: "Second Checking", mask: "5150" } ])
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+
+ assert_duplicate_warning do
+ assert_select "a[href=?]", edit_plaid_item_path(first, add_accounts: true)
+ assert_select "a[href=?]", edit_plaid_item_path(second, add_accounts: true)
+ assert_select "h2", text: I18n.t("plaid_items.duplicate_warning.title", count: 2)
+ end
+ assert_match "First Checking", response.body
+ assert_match "Second Checking", response.body
+ # One update action could not say which connection it updates, so each card
+ # carries its own, ahead of the warning's shared actions.
+ assert_equal [ update_label, update_label, close_label, confirm_label ], warning_actions
+ end
+
+ # When the accounts match, the warning is about the connection that holds them. A
+ # second login's connection at the same institution has nothing to do with it, and
+ # listing it would make "this connection" ambiguous.
+ test "create lists only the matching connection when every account is already connected" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Example Checking", mask: "4321" } ])
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Business Checking", mask: "9999" } ])
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank",
+ accounts: [ { name: "Example Checking", mask: "4321" } ])
+
+ assert_duplicate_warning do
+ assert_select "h2", text: I18n.t("plaid_items.duplicate_warning.title_all_connected")
+ end
+ assert_match "Example Checking", response.body
+ assert_no_match "Business Checking", response.body
+ end
+
+ # Updating has to reach the connection the link overlaps. With an unrelated login's
+ # connection listed too, each would get its own update action, and the user could
+ # update the wrong one.
+ test "create lists only the overlapping connection when some accounts are new" do
+ matching = create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Example Checking", mask: "4321" } ])
+ unrelated = create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Business Checking", mask: "9999" } ])
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank",
+ accounts: [ { name: "Example Checking", mask: "4321" }, { name: "Example HSA", mask: "7777" } ])
+
+ assert_duplicate_warning do
+ assert_select "a[href=?]", edit_plaid_item_path(matching, add_accounts: true)
+ assert_select "a[href=?]", edit_plaid_item_path(unrelated, add_accounts: true), count: 0
+ assert_select "h2", text: I18n.t("plaid_items.duplicate_warning.title", count: 1)
+ end
+ assert_no_match "Business Checking", response.body
+ assert_equal [ update_label, close_label, confirm_label ], warning_actions
+ end
+
+ # The different-login case: nothing matches, so no connection is the one this link
+ # overlaps, and every connection at the institution stays listed as context.
+ test "create lists every connection when none of the accounts match" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Example Checking", mask: "4321" } ])
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Business Checking", mask: "9999" } ])
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank",
+ accounts: [ { name: "Other Checking", mask: "1111" } ])
+
+ assert_duplicate_warning do
+ assert_select "p", text: I18n.t("plaid_items.duplicate_warning.overlap.none_connected")
+ assert_select "h2", text: I18n.t("plaid_items.duplicate_warning.title", count: 2)
+ end
+ assert_match "Example Checking", response.body
+ assert_match "Business Checking", response.body
+ assert_equal [ confirm_label, close_label ], warning_actions
+ end
+
+ test "create titles a single match in the singular" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin))
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+
+ assert_duplicate_warning do
+ assert_select "h2", text: I18n.t("plaid_items.duplicate_warning.title", count: 1)
+ end
+ end
+
+ # Link reports the new connection's accounts -- whichever the user selected, or all of
+ # them when Plaid preselects or skips account selection -- so the warning says whether
+ # they are already connected instead of asking which login the user signed in with.
+ # When all of them are, this is the same connection made twice, and the title says so.
+ test "create says when every account in the new connection is already connected" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Example Checking", mask: "4321" }, { name: "Example Savings", mask: "8765" } ])
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank",
+ accounts: [ { name: "Example Checking", mask: "4321" }, { name: "Example Savings", mask: "8765" } ])
+
+ assert_duplicate_warning do
+ assert_select "h2", text: I18n.t("plaid_items.duplicate_warning.title_all_connected")
+ assert_select "p", text: I18n.t("plaid_items.duplicate_warning.overlap.all_connected", count: 2)
+ end
+ end
+
+ # When every account already matches, adding the connection can only duplicate them
+ # and spend a Plaid connection, so Close is the only action. The text says where to
+ # go instead: Add accounts on the existing connection for more accounts, or New
+ # account again with the other login, named for the institution. Without the form,
+ # the held token never reaches the page at all.
+ test "create offers only Close when every account is already connected" do
+ item = create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Example Checking", mask: "4321" } ])
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank",
+ accounts: [ { name: "Example Checking", mask: "4321" } ])
+
+ assert_duplicate_warning do
+ assert_select "a[href=?]", edit_plaid_item_path(item, add_accounts: true), count: 0
+ assert_select "p", text: I18n.t("plaid_items.duplicate_warning.overlap.more_accounts", institution: "Example Bank")
+ assert_select "p", text: /Add accounts on the Example Bank connection/
+ assert_select "p", text: I18n.t("plaid_items.duplicate_warning.overlap.different_login", institution: "Example Bank")
+ assert_select "p", text: /different Example Bank login/
+ end
+ assert_equal [ close_label ], warning_actions
+ assert_no_match HELD_TOKEN, response.body
+ end
+
+ # Link may report an institution id without a name. The connection already on
+ # record carries the same institution's name, so the advice uses that instead of
+ # leaving a gap where the name belongs.
+ test "create names the institution from the existing connection when Link sends no name" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Example Checking", mask: "4321" } ])
+
+ post_link(institution_id: "ins_example", institution_name: "",
+ accounts: [ { name: "Example Checking", mask: "4321" } ])
+
+ assert_duplicate_warning do
+ assert_select "p", text: /different Example Bank login/
+ end
+ end
+
+ # Plaid doesn't support adding accounts to an EU connection, so there is no Add
+ # accounts to point at.
+ test "create leaves out the add-accounts advice for an eu connection" do
+ create_plaid_item(name: "EU Bank", institution_id: "ins_eu", region: :eu, owner: users(:family_admin),
+ accounts: [ { name: "EU Checking", mask: "4321" } ])
+
+ post_link(institution_id: "ins_eu", institution_name: "EU Bank", region: "eu",
+ accounts: [ { name: "EU Checking", mask: "4321" } ])
+
+ assert_duplicate_warning do
+ assert_select "p", text: /Add accounts on the/, count: 0
+ assert_select "p", text: /different EU Bank login/
+ end
+ end
+
+ # Without masks there is only a name to compare, and a different login's generic
+ # "Brokerage" account can share it. So the warning stays general and keeps the
+ # override instead of declaring the accounts already connected.
+ test "create keeps the override when the reported accounts have no masks" do
+ create_plaid_item(name: "Example Brokerage", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Brokerage", mask: nil } ])
+
+ post_link(institution_id: "ins_example", institution_name: "Example Brokerage",
+ accounts: [ { name: "Brokerage", mask: "" } ])
+
+ assert_duplicate_warning do
+ assert_select "p", text: I18n.t("plaid_items.duplicate_warning.overlap.unknown", count: 1)
+ assert_select "form[action=?]", plaid_items_path
+ end
+ end
+
+ # Some accounts are new, and the likeliest reason is the same login with more
+ # accounts chosen this time -- so updating the existing connection, which adds them
+ # without a second connection, leads. Confirming stays, last, for a different login
+ # that shares an account such as a joint account, though it duplicates that account.
+ test "create lists the new connection's accounts that are not connected yet" do
+ item = create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Example Checking", mask: "4321" } ])
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank",
+ accounts: [ { name: "Example Checking", mask: "4321" }, { name: "Example HSA", mask: "7777" } ])
+
+ assert_duplicate_warning do
+ assert_select "p", text: I18n.t("plaid_items.duplicate_warning.overlap.some_connected.unconnected", count: 1)
+ assert_select "dl > div", text: /Example HSA\s*\*{4}7777/
+ assert_select "p", text: I18n.t("plaid_items.duplicate_warning.overlap.some_connected.connected", count: 1)
+ assert_select "a[href=?]", edit_plaid_item_path(item, add_accounts: true)
+ end
+ assert_equal [ update_label, close_label, confirm_label ], warning_actions
+ end
+
+ # The warning argues both sides. A second login with different accounts duplicates
+ # nothing, and saying so matters more than the warning itself: a warning that is
+ # false for the people the override serves costs more than an unneeded one. It
+ # still appears, so a renamed account can't carry a real duplicate past it, but
+ # confirming leads.
+ test "create says when none of the new connection's accounts are connected" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Example Checking", mask: "4321" } ])
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank",
+ accounts: [ { name: "Business Checking", mask: "9999" } ])
+
+ assert_duplicate_warning do
+ assert_select "p", text: I18n.t("plaid_items.duplicate_warning.overlap.none_connected")
+ end
+ assert_equal [ confirm_label, close_label ], warning_actions
+ end
+
+ # The likeliest reason there is nothing to compare is a connection whose first sync
+ # never landed -- a broken one the user is trying to fix -- so updating it is offered
+ # beside confirming, with Close leading because neither is clearly right.
+ test "create falls back to general copy when Link reports no accounts" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Example Checking", mask: "4321" } ])
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+
+ assert_duplicate_warning do
+ assert_select "p", text: I18n.t("plaid_items.duplicate_warning.overlap.unknown", count: 1)
+ end
+ assert_equal [ close_label, update_label, confirm_label ], warning_actions
+ end
+
+ # owner_id is nullable and `owned_by?` is false for a null owner, so the attribution
+ # line would otherwise render for connections predating per-user ownership (#3613).
+ # An admin sees every family connection, so this is reachable rather than theoretical.
+ test "create omits attribution for a connection with no owner" do
+ item = create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin))
+ item.update_column(:owner_id, nil)
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+
+ assert_duplicate_warning
+ # assert_no_match on the body rather than assert_select: the selector strips the
+ # element's text, so a pattern ending in the interpolation's leading space silently
+ # matches nothing and the test passes whether or not the line renders.
+ assert_no_match(/Connected by/, response.body)
+ end
+
+ # Whether to duplicate a connection or keep the existing one is not a choice a
+ # stray click should make -- the dialog opens as Link closes, wherever Link left
+ # the pointer.
+ test "create does not let a stray click dismiss the warning" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin))
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+
+ assert_duplicate_warning do
+ # Lowercased: HTML parsers downcase attribute names, so the selector cannot use
+ # the `DS` casing that appears in the source.
+ assert_select "dialog[data-ds--dialog-disable-click-outside-value=?]", "true"
+ end
+ end
+
+ # The warning carries a live public token. Turbo would otherwise keep it in the page
+ # snapshot it caches on navigation, and Back would restore a dialog able to spend it.
+ test "create keeps the warning out of Turbo's page cache" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin))
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+
+ assert_duplicate_warning do
+ assert_select "dialog[data-turbo-temporary]"
+ end
+ end
+
+ # Plaid only changes an existing connection through an update-mode session, so the
+ # route to more accounts runs through the existing connection, not a new one.
+ test "create offers the add-accounts route for a us connection" do
+ item = create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin))
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+
+ assert_duplicate_warning do
+ assert_select "a[href=?]", edit_plaid_item_path(item, add_accounts: true), text: update_label
+ end
+ end
+
+ # GET edit mints a Plaid update-mode link token as a side effect, so a hover prefetch
+ # would call /link/token/create each time the pointer crossed the button. Found in
+ # the dev log against Plaid Sandbox: four prefetches, no click.
+ test "create keeps Turbo from prefetching the add-accounts route" do
+ item = create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin))
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+
+ assert_duplicate_warning do
+ assert_select "a[href=?][data-turbo-prefetch=?][data-turbo-frame=?]",
+ edit_plaid_item_path(item, add_accounts: true), "false", "modal"
+ end
+ end
+
+ # Close leaves everything as it was: it dismisses the warning, and the held token is
+ # never exchanged.
+ test "create lets the user close the warning without adding anything" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin))
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+
+ assert_duplicate_warning do
+ assert_select "button[type=button][data-action~=?]", "DS--dialog#close", text: close_label
+ end
+ end
+
+ # Update mode only accepts account selection for US items, so the link would be
+ # inert for an EU connection.
+ test "create omits the add-accounts route for an eu connection" do
+ item = create_plaid_item(name: "EU Bank", institution_id: "ins_eu", region: :eu, owner: users(:family_admin))
+
+ post_link(institution_id: "ins_eu", institution_name: "EU Bank", region: "eu")
+
+ assert_duplicate_warning do
+ assert_select "a[href=?]", edit_plaid_item_path(item, add_accounts: true), count: 0
+ # assert_select rather than assert_match: the copy contains an apostrophe, which
+ # is HTML-escaped in the body but decoded by the selector's text matcher.
+ assert_select "p", text: /support adding accounts to an existing/
+ end
+ end
+
+ # Updating needs a connection this user may manage. Without one, closing and
+ # confirming remain, whatever a listed connection lets this user do.
+ test "create offers both choices even when no connection is actionable" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin))
+ PlaidItem.any_instance.stubs(:manageable_by?).returns(false)
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+
+ assert_duplicate_warning do
+ assert_select "a[href*=?]", "add_accounts", count: 0
+ assert_select "form[action=?]", plaid_items_path
+ end
+ assert_equal [ close_label, confirm_label ], warning_actions
+ end
+
+ # Nothing is exchanged until the user picks "Confirm this connection", so that form has
+ # to carry the held token back, along with everything create needs to name and
+ # scope the connection, and the flag that lets it past the gate.
+ test "create's warning carries the held token back for the override" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin))
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+
+ assert_duplicate_warning do
+ assert_select "form[action=?][method=post]", plaid_items_path do
+ assert_select "input[type=hidden][name=?][value=?]", "plaid_item[public_token]", HELD_TOKEN
+ assert_select "input[type=hidden][name=?][value=?]", "plaid_item[region]", "us"
+ assert_select "input[type=hidden][name=?][value=?]", "plaid_item[metadata][institution][institution_id]", "ins_example"
+ assert_select "input[type=hidden][name=?][value=?]", "plaid_item[metadata][institution][name]", "Example Bank"
+ assert_select "input[type=hidden][name=?][value=?]", "confirm_duplicate", "1"
+ # _top: a confirmed create redirects to Accounts, which has no modal frame.
+ assert_select "button[data-turbo-frame=?]", "_top"
+ end
+ end
+ end
+
+ # An item whose first sync never landed has no institution_id, and a broken
+ # connection is exactly what a user tries to re-link. Fall back to the stored name.
+ test "create matches on name when the connection has no institution_id" do
+ create_plaid_item(name: "Chase", institution_id: nil, owner: users(:family_admin))
+ stub_plaid_provider.expects(:exchange_public_token).never
+
+ post_link(institution_id: "ins_56", institution_name: "CHASE ")
+
+ assert_duplicate_warning
+ assert_match "Chase", response.body
+ end
+
+ # A confirmed institution_id mismatch plus a shared display name is a false
+ # positive, not a match -- the fallback is only for rows with no id at all.
+ test "create exchanges when only the name matches a connection with an institution_id" do
+ create_plaid_item(name: "Chase", institution_id: "ins_chase", owner: users(:family_admin))
+
+ assert_exchanges do
+ post_link(institution_id: "ins_other", institution_name: "Chase")
+ end
+ end
+
+ # Link can leave the institution id out. With no id to compare, the name is the only
+ # evidence left, so it decides even for a connection whose id is known.
+ test "create matches on name when Link reports no institution_id" do
+ create_plaid_item(name: "Chase", institution_id: "ins_56", owner: users(:family_admin))
+ stub_plaid_provider.expects(:exchange_public_token).never
+
+ post_link(institution_id: nil, institution_name: "Chase")
+
+ assert_duplicate_warning
+ end
+
+ test "create exchanges when the matching connection is scheduled for deletion" do
+ item = create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin))
+ item.update!(scheduled_for_deletion: true)
+
+ assert_exchanges do
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+ end
+ end
+
+ test "create exchanges when the matching connection is in the other region" do
+ create_plaid_item(name: "EU Bank", institution_id: "ins_eu", region: :eu, owner: users(:family_admin))
+
+ assert_exchanges do
+ post_link(institution_id: "ins_eu", institution_name: "EU Bank")
+ end
+ end
+
+ test "create exchanges when only another family has the institution" do
+ create_plaid_item(family: families(:empty), name: "Example Bank", institution_id: "ins_example", owner: users(:empty))
+
+ assert_exchanges do
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+ end
+ end
+
+ # PlaidItem declares `credential_scope :per_connection`, so two housemates linking
+ # their own logins at one bank hold two legitimate Items -- and a member's view of
+ # the family exposes nothing of anyone else's connections.
+ test "create does not hold a member's link on someone else's connection" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin))
+ sign_in users(:family_member)
+
+ assert_exchanges do
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+ end
+ end
+
+ # Admins keep family-wide oversight, and the harm is family-wide too: the family
+ # shares one Plaid client and one Item allowance, so a member's existing connection
+ # really does mean an admin's new one spends a second slot.
+ test "create holds an admin's link on a member's connection" do
+ member_item = create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_member))
+ stub_plaid_provider.expects(:exchange_public_token).never
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank")
+
+ assert_duplicate_warning do
+ assert_select "a[href=?]", edit_plaid_item_path(member_item, add_accounts: true), count: 0
+ end
+ assert_equal [ close_label, confirm_label ], warning_actions
+ end
+
+ # An admin can see and manage a member's connection, but update mode signs in with
+ # that connection's bank login, which is the member's. When the link overlaps only
+ # with another member's connection -- through a shared joint account, say -- it is
+ # a different login, so there is no update action and confirming leads.
+ test "create leads with confirming when only another member's connection overlaps" do
+ member_item = create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_member),
+ accounts: [ { name: "Joint Checking", mask: "4321" } ])
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank",
+ accounts: [ { name: "Joint Checking", mask: "4321" }, { name: "Admin Savings", mask: "5555" } ])
+
+ assert_duplicate_warning do
+ assert_select "a[href=?]", edit_plaid_item_path(member_item, add_accounts: true), count: 0
+ end
+ assert_equal [ confirm_label, close_label ], warning_actions
+ end
+
+ # Two people's own logins can reach the same joint accounts. When every account
+ # matches another member's connection, the user didn't make "this connection", and
+ # a different login is exactly what they used -- so the warning says whose
+ # connection already has the accounts. Close stays the only action, since adding
+ # would still only duplicate them.
+ test "create says another member already connected the accounts" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_member),
+ accounts: [ { name: "Joint Checking", mask: "4321" }, { name: "Joint Savings", mask: "8765" } ])
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank",
+ accounts: [ { name: "Joint Checking", mask: "4321" }, { name: "Joint Savings", mask: "8765" } ])
+
+ assert_duplicate_warning do
+ assert_select "h2", text: I18n.t("plaid_items.duplicate_warning.title_others_connected", count: 2)
+ assert_select "p", text: I18n.t("plaid_items.duplicate_warning.overlap.others_connected",
+ count: 2, name: users(:family_member).display_name)
+ assert_select "p", text: /connect a different/, count: 0
+ end
+ assert_equal [ close_label ], warning_actions
+ end
+
+ # Accounts spread across several other members' connections have no single name to
+ # give, so the warning names no one.
+ test "create names no one when other members' connections share the accounts" do
+ second_member = User.create!(family: families(:dylan_family), email: "[email protected]",
+ first_name: "Second", last_name: "Member", password: "password", role: :member)
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_member),
+ accounts: [ { name: "Joint Checking", mask: "4321" } ])
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: second_member,
+ accounts: [ { name: "Joint Savings", mask: "8765" } ])
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank",
+ accounts: [ { name: "Joint Checking", mask: "4321" }, { name: "Joint Savings", mask: "8765" } ])
+
+ assert_duplicate_warning do
+ assert_select "p", text: I18n.t("plaid_items.duplicate_warning.overlap.others_connected_several", count: 2)
+ end
+ end
+
+ # A member's connection holding the same accounts doesn't change that the user made
+ # this connection too, so their own connection decides the wording.
+ test "create says you made the connection when yours and a member's share the accounts" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Joint Checking", mask: "4321" } ])
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_member),
+ accounts: [ { name: "Joint Checking", mask: "4321" } ])
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank",
+ accounts: [ { name: "Joint Checking", mask: "4321" } ])
+
+ assert_duplicate_warning do
+ assert_select "h2", text: I18n.t("plaid_items.duplicate_warning.title_all_connected")
+ assert_select "p", text: I18n.t("plaid_items.duplicate_warning.overlap.all_connected", count: 1)
+ end
+ end
+
+ # Connections from before per-user ownership have no owner, and admins have always
+ # managed them, so an admin keeps the update action on those.
+ test "create offers an admin the update for a connection with no owner" do
+ item = create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin),
+ accounts: [ { name: "Example Checking", mask: "4321" } ])
+ item.update_column(:owner_id, nil)
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank",
+ accounts: [ { name: "Example Checking", mask: "4321" }, { name: "Example HSA", mask: "7777" } ])
+
+ assert_duplicate_warning do
+ assert_select "a[href=?]", edit_plaid_item_path(item, add_accounts: true)
+ end
+ assert_equal [ update_label, close_label, confirm_label ], warning_actions
+ end
+
+ test "create denies a guest" do
+ guest = users(:family_member)
+ guest.update!(role: :guest)
+ sign_in guest
+ stub_plaid_provider.expects(:exchange_public_token).never
+
+ post_link(institution_id: "ins_example", institution_name: "Example Bank", confirm: true)
+
+ assert_response :forbidden
+ end
+
+ # A held token can outlive its 30-minute lifetime while the warning sits open, and
+ # Plaid reports an expired token and an already-exchanged one the same way.
+ test "create asks the user to connect again when Plaid rejects the held token" do
+ stub_plaid_provider.expects(:exchange_public_token).raises(
+ Plaid::ApiError.new(code: 400, response_body: {
+ "error_type" => "INVALID_INPUT",
+ "error_code" => "INVALID_PUBLIC_TOKEN",
+ "error_message" => "could not find matching public token"
+ }.to_json)
+ )
+
+ assert_no_difference "PlaidItem.count" do
+ assert_difference "DebugLogEntry.count", 1 do
+ post_link(institution_id: "ins_example", institution_name: "Example Bank", confirm: true)
+ end
+ end
+
+ assert_select "turbo-stream[action=redirect][target=?]", accounts_path
+ assert_equal I18n.t("plaid_items.create.token_expired"), flash[:alert]
+ assert_no_match HELD_TOKEN, DebugLogEntry.order(:created_at).last.attributes.to_json
+ end
+
+ test "create redirects with a generic alert when the exchange fails otherwise" do
+ stub_plaid_provider.expects(:exchange_public_token).raises(
+ Plaid::ApiError.new(code: 500, response_body: { "error_code" => "INTERNAL_SERVER_ERROR" }.to_json)
+ )
+
+ post plaid_items_url, params: {
+ plaid_item: { public_token: HELD_TOKEN, region: "us", metadata: { institution: { name: "Example Bank" } } }
+ }
+
+ assert_redirected_to accounts_path
+ assert_equal I18n.t("plaid_items.create.exchange_failed"), flash[:alert]
+ end
+
+ # create answers plain HTML as well as streams, and a page can't render the
+ # warning's stream. A held request that wants HTML goes back to Accounts with the
+ # reason instead, and still exchanges nothing.
+ test "create redirects a plain HTML request when the institution is already connected" do
+ create_plaid_item(name: "Example Bank", institution_id: "ins_example", owner: users(:family_admin))
+ stub_plaid_provider.expects(:exchange_public_token).never
+
+ assert_no_difference("PlaidItem.count") do
+ post plaid_items_url, params: {
+ plaid_item: {
+ public_token: HELD_TOKEN,
+ region: "us",
+ metadata: { institution: { name: "Example Bank", institution_id: "ins_example" } }
+ }
+ }
+ end
+
+ assert_redirected_to accounts_path
+ assert_equal I18n.t("plaid_items.create.already_connected"), flash[:alert]
+ end
+
+ # A hidden field has no nil: an institution id Link never reported comes back from
+ # the warning's form as an empty string, which must not be stored as an id.
+ test "create stores no institution_id when the form carries a blank one" do
+ assert_exchanges do
+ post_link(institution_id: "", institution_name: "Example Bank", confirm: true)
+ end
+
+ assert_nil PlaidItem.order(:created_at).last.institution_id
+ end
+
+ private
+ # Link's onSuccess, as plaid_controller.js forwards it: the institution and its
+ # accounts under metadata, and an Accept header that takes a Turbo Stream.
+ def post_link(institution_id:, institution_name:, region: "us", confirm: false, accounts: nil)
+ metadata = { institution: { name: institution_name, institution_id: institution_id } }
+ metadata[:accounts] = accounts if accounts
+
+ params = {
+ plaid_item: {
+ public_token: HELD_TOKEN,
+ region: region,
+ metadata: metadata
+ }
+ }
+ params[:confirm_duplicate] = "1" if confirm
+
+ post plaid_items_url, params: params, as: :turbo_stream
+ end
+
+ def stub_plaid_provider(region: "us")
+ provider = mock
+ Provider::Registry.stubs(:plaid_provider_for_region).with(region).returns(provider)
+ provider
+ end
+
+ # The warning replaces the modal frame. Scoping to the stream's template keeps a
+ # match anywhere else in the body from satisfying the block's assertions.
+ def assert_duplicate_warning(&block)
+ assert_response :success
+ assert_select "turbo-stream[action=replace][target=modal] > template", &block
+ end
+
+ # The warning's actions, by label, in the order they appear. The header's
+ # icon-only close button has no label, and an EU card's link to Accounts is
+ # guidance on that connection rather than one of the warning's choices.
+ def warning_actions
+ template = css_select("turbo-stream[action=replace][target=modal] > template").first
+ labels = template.css("a, button").map { |node| node.text.squish }.reject(&:blank?)
+ labels - [ I18n.t("plaid_items.duplicate_warning.manage_connection") ]
+ end
+
+ def close_label
+ I18n.t("plaid_items.duplicate_warning.close")
+ end
+
+ def update_label
+ I18n.t("plaid_items.duplicate_warning.update_existing")
+ end
+
+ def confirm_label
+ I18n.t("plaid_items.duplicate_warning.confirm")
+ end
+
+ # One exchange, one new connection, and a stream back to Accounts -- the outcome
+ # whenever the gate has nothing to hold.
+ def assert_exchanges
+ stub_plaid_provider.expects(:exchange_public_token).with(HELD_TOKEN).once.returns(
+ OpenStruct.new(access_token: "access-sandbox-held", item_id: "item-sandbox-#{SecureRandom.hex(4)}")
+ )
+
+ assert_difference("PlaidItem.count", 1) { yield }
+ assert_select "turbo-stream[action=redirect][target=?]", accounts_path
+ end
+
+ # Built inline rather than as fixtures so the surrounding suites keep the Plaid
+ # item counts they were written against.
+ def create_plaid_item(family: families(:dylan_family), name:, institution_id: nil, region: :us, owner: nil, accounts: [])
+ item = family.plaid_items.create!(
+ name: name,
+ plaid_id: "item_#{SecureRandom.hex(6)}",
+ access_token: "access-#{SecureRandom.hex(6)}",
+ plaid_region: region,
+ institution_id: institution_id,
+ owner: owner
+ )
+
+ accounts.each do |attrs|
+ item.plaid_accounts.create!(
+ {
+ plaid_id: "acct_#{SecureRandom.hex(6)}",
+ currency: "USD",
+ plaid_type: "depository",
+ plaid_subtype: "checking",
+ current_balance: 100,
+ available_balance: 100
+ }.merge(attrs)
+ )
+ end
+
+ item
+ end
end
diff --git a/test/models/family/plaid_connectable_test.rb b/test/models/family/plaid_connectable_test.rb
new file mode 100644
index 0000000000..0837f85dd3
--- /dev/null
+++ b/test/models/family/plaid_connectable_test.rb
@@ -0,0 +1,46 @@
+require "test_helper"
+require "ostruct"
+
+class Family::PlaidConnectableTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @provider = mock
+ Provider::Registry.stubs(:plaid_provider_for_region).with(:us).returns(@provider)
+ end
+
+ test "create_plaid_item! persists the institution id it is given" do
+ stub_exchange
+
+ item = @family.create_plaid_item!(
+ public_token: "public-sandbox-1234",
+ item_name: "Example Bank",
+ region: :us,
+ institution_id: "ins_example"
+ )
+
+ assert_equal "ins_example", item.institution_id
+ end
+
+ # institution_id is optional because this is a public model API and the column was
+ # only ever populated during the first sync, by upsert_plaid_institution_snapshot!.
+ # A caller that does not have the Link metadata must still be able to create an item.
+ test "create_plaid_item! works without an institution id" do
+ stub_exchange
+
+ item = @family.create_plaid_item!(
+ public_token: "public-sandbox-1234",
+ item_name: "Example Bank",
+ region: :us
+ )
+
+ assert_nil item.institution_id
+ assert_equal "Example Bank", item.name
+ end
+
+ private
+ def stub_exchange
+ @provider.expects(:exchange_public_token).returns(
+ OpenStruct.new(access_token: "access-sandbox-1234", item_id: "item-sandbox-#{SecureRandom.hex(4)}")
+ )
+ end
+end
diff --git a/test/models/plaid_item/account_overlap_test.rb b/test/models/plaid_item/account_overlap_test.rb
new file mode 100644
index 0000000000..05c80dfc17
--- /dev/null
+++ b/test/models/plaid_item/account_overlap_test.rb
@@ -0,0 +1,115 @@
+require "test_helper"
+
+class PlaidItem::AccountOverlapTest < ActiveSupport::TestCase
+ FakeItem = Struct.new(:plaid_accounts)
+ FakeAccount = Struct.new(:name, :mask)
+
+ setup do
+ @item = FakeItem.new([ FakeAccount.new("Plaid Checking", "0000"), FakeAccount.new("Plaid Saving", "1111") ])
+ end
+
+ test "all accounts are connected when every reported account matches by name and mask" do
+ overlap = overlap_for([ reported("Plaid Checking", "0000"), reported("Plaid Saving", "1111") ])
+
+ assert_equal :all_connected, overlap.state
+ assert_equal 2, overlap.connected_count
+ assert_empty overlap.unconnected_accounts
+ end
+
+ test "some accounts are connected when only part of the new connection matches" do
+ overlap = overlap_for([ reported("Plaid Checking", "0000"), reported("Plaid HSA", "7777") ])
+
+ assert_equal :some_connected, overlap.state
+ assert_equal [ reported("Plaid HSA", "7777") ], overlap.unconnected_accounts
+ assert_equal 1, overlap.connected_count
+ end
+
+ test "no accounts are connected when nothing reported matches" do
+ overlap = overlap_for([ reported("Business Checking", "9999") ])
+
+ assert_equal :none_connected, overlap.state
+ assert_equal 0, overlap.connected_count
+ end
+
+ # Plaid often names accounts generically ("Plaid Checking", "Checking"), so a second
+ # login's accounts can share names with the first's. The mask has to agree too.
+ test "a matching name with a different mask is not connected" do
+ overlap = overlap_for([ reported("Plaid Checking", "4242") ])
+
+ assert_equal :none_connected, overlap.state
+ end
+
+ test "names match regardless of case and surrounding whitespace" do
+ overlap = overlap_for([ reported(" plaid CHECKING ", "0000") ])
+
+ assert_equal :all_connected, overlap.state
+ end
+
+ test "every matching connection counts" do
+ other = FakeItem.new([ FakeAccount.new("Plaid HSA", "7777") ])
+
+ overlap = overlap_for([ reported("Plaid Checking", "0000"), reported("Plaid HSA", "7777") ], items: [ @item, other ])
+
+ assert_equal :all_connected, overlap.state
+ end
+
+ test "the comparison is unknown when Link reports no accounts" do
+ assert_equal :unknown, overlap_for([]).state
+ assert_equal :unknown, overlap_for(nil).state
+ end
+
+ # A connection whose first sync never landed has no accounts on record, so anything
+ # Link reported might be one of its accounts -- "none connected" would be a guess.
+ test "the comparison is unknown when a matching connection has no accounts on record" do
+ unsynced = FakeItem.new([])
+
+ overlap = overlap_for([ reported("Business Checking", "9999") ], items: [ @item, unsynced ])
+
+ assert_equal :unknown, overlap.state
+ end
+
+ # Brokerages and crypto exchanges often report no mask and generic names such as
+ # "Brokerage", so a different login's accounts can match a connected one on name
+ # alone. That is too little to call them the same, and an all-connected verdict
+ # would take away the dialog's override.
+ test "the comparison is unknown when a reported account has no mask" do
+ brokerage = FakeItem.new([ FakeAccount.new("Brokerage", nil) ])
+
+ assert_equal :unknown, overlap_for([ reported("Brokerage", nil) ], items: [ brokerage ]).state
+ assert_equal :unknown, overlap_for([ reported("Brokerage", ""), reported("Plaid Checking", "0000") ], items: [ brokerage, @item ]).state
+ end
+
+ # A family can hold several connections at one institution, often for different
+ # logins. Only those holding a reported account are what this link overlaps.
+ test "matching items are the connections holding a reported account" do
+ business = FakeItem.new([ FakeAccount.new("Business Checking", "9999") ])
+
+ overlap = overlap_for([ reported("Plaid Checking", "0000") ], items: [ @item, business ])
+
+ assert_equal [ @item ], overlap.matching_items
+ end
+
+ test "matching items are empty when nothing reported matches" do
+ business = FakeItem.new([ FakeAccount.new("Business Checking", "9999") ])
+
+ overlap = overlap_for([ reported("Other Checking", "4242") ], items: [ @item, business ])
+
+ assert_equal :none_connected, overlap.state
+ assert_empty overlap.matching_items
+ end
+
+ test "reported accounts may arrive with symbol keys" do
+ overlap = overlap_for([ { name: "Plaid Checking", mask: "0000" } ])
+
+ assert_equal :all_connected, overlap.state
+ end
+
+ private
+ def overlap_for(link_accounts, items: [ @item ])
+ PlaidItem::AccountOverlap.new(link_accounts: link_accounts, plaid_items: items)
+ end
+
+ def reported(name, mask)
+ { "name" => name, "mask" => mask }
+ end
+end
diff --git a/test/system/plaid_link_test.rb b/test/system/plaid_link_test.rb
new file mode 100644
index 0000000000..1033564fe8
--- /dev/null
+++ b/test/system/plaid_link_test.rb
@@ -0,0 +1,95 @@
+require "application_system_test_case"
+
+# Plaid Link can't run here, so each test puts a stand-in on window.Plaid that
+# finishes at once, as Link's onSuccess would, and the real Stimulus controller
+# takes it from there.
+class PlaidLinkTest < ApplicationSystemTestCase
+ setup do
+ provider = mock
+ provider.stubs(:get_link_token).returns(OpenStruct.new(link_token: "link-sandbox-test"))
+ Provider::Registry.stubs(:plaid_provider_for_region).returns(provider)
+
+ sign_in users(:family_admin)
+ end
+
+ test "shows the duplicate warning the server sends" do
+ families(:dylan_family).plaid_items.create!(
+ name: "Example Bank",
+ plaid_id: "item_system_test",
+ access_token: "access-system-test",
+ plaid_region: :us,
+ institution_id: "ins_example",
+ owner: users(:family_admin)
+ )
+
+ finish_link
+
+ assert_selector "dialog", text: I18n.t("plaid_items.duplicate_warning.title", count: 1)
+ assert_no_selector "#notification-tray", text: create_failed_message
+ end
+
+ # Link has closed by the time the request fails, so nothing else on the page
+ # changes to say so.
+ test "says so when the request to add the connection fails" do
+ answer_create_with "Promise.reject(new TypeError('Failed to fetch'))"
+
+ finish_link
+
+ assert_selector "#notification-tray", text: create_failed_message
+ end
+
+ test "says so when the server can't add the connection" do
+ answer_create_with "Promise.resolve(new Response('', { status: 500 }))"
+
+ finish_link
+
+ assert_selector "#notification-tray", text: create_failed_message
+ end
+
+ private
+ def create_failed_message
+ I18n.t("plaid_items.auto_link_opener.create_failed")
+ end
+
+ # Opens Link the way the account-type screen does, into the modal frame.
+ def finish_link
+ execute_script(<<~JS)
+ // The controller sends the page's CSRF token, and the test environment, with
+ // forgery protection off, renders no token to send.
+ if (!document.querySelector('meta[name="csrf-token"]')) {
+ document.head.insertAdjacentHTML("beforeend", '<meta name="csrf-token" content="system-test">');
+ }
+
+ window.Plaid = {
+ create: (config) => ({
+ open: () => config.onSuccess("public-sandbox-test", {
+ institution: { name: "Example Bank", institution_id: "ins_example" },
+ accounts: []
+ }),
+ destroy: () => {}
+ })
+ };
+
+ const link = document.createElement("a");
+ link.id = "open-plaid-link";
+ link.href = "/plaid_items/new?region=us";
+ link.dataset.turboFrame = "modal";
+ link.textContent = "Open Plaid Link";
+ // The app's layout fills the viewport, so a link merely appended to the body
+ // is scrolled out of reach.
+ link.style.cssText = "position: fixed; top: 0; left: 0; z-index: 100;";
+ document.body.append(link);
+ JS
+
+ find("#open-plaid-link").click
+ end
+
+ # Replaces the browser's answer to the request that adds the connection, and only
+ # that one, since Turbo fetches the modal frame through the same function.
+ def answer_create_with(response)
+ execute_script(<<~JS)
+ const fetchOriginal = window.fetch;
+ window.fetch = (url, options) => url === "/plaid_items" ? #{response} : fetchOriginal(url, options);
+ JS
+ end
+end