SimpleFIN: setup UX + same-provider relink + card-replacement detection (#1493)

* SimpleFIN: setup UX + same-provider relink + card-replacement detection

Fixes three bugs and adds auto-detection for credit-card fraud replacement.

Bugs:
- Importer: per-institution auth errors no longer flip the whole item to
  requires_update. Partial errors stay on sync_stats so other institutions
  keep syncing.
- Setup page: new activity badges (recent / dormant / empty / likely-closed)
  via SimplefinAccount::ActivitySummary. Likely-closed (dormant + near-zero
  balance + prior history) defaults to "skip" in the type picker.
- Relink: link_existing_account allows SimpleFIN to SimpleFIN swaps by
  atomically detaching the old AccountProvider inside a transaction. Adds
  "Change SimpleFIN account" menu item on linked-account dropdowns.

Feature (credit-card scope only):
- SimplefinItem::ReplacementDetector runs post-sync. Pairs a linked dormant
  zero-balance sfa with an unlinked active sfa at the same institution and
  account type. Persists suggestions on Sync#sync_stats.
- Inline banner on the SimpleFIN item card prompts relink via CustomConfirm.
  Per-pair dismiss button scoped to the current sync (resurfaces on next
  sync if still applicable). Auto-suppresses once the relink has landed.

Dev tooling:
- bin/rails simplefin:seed_fraud_scenario[email] creates a realistic broken
  pair for manual QA; cleanup_fraud_scenario reverses it.

* Address review feedback on #1493

- ReplacementDetector: symmetric one-to-one matching. Two dormant cards
  pointing at the same active card are now both skipped — previously the
  detector could emit two suggestions that would clobber each other if
  the user accepted both.
- ReplacementDetector: require non-blank institution names on both sides
  before matching. Blank-vs-blank was accidentally treated as equal,
  risking cross-provider false matches when SimpleFIN omitted org_data.
- ActivitySummary: fall back to "posted" when "transacted_at" is 0
  (SimpleFIN's "unknown" sentinel). Integer 0 is truthy in Ruby, so the
  previous `|| fallback` short-circuited and ignored posted.
- Controller: dismiss key is now the (dormant, active) pair so dismissing
  one candidate for a dormant card doesn't suppress others.
- Helper test: freeze time around "6.hours.ago" and "5.days.ago"
  assertions so they don't flake when the suite runs before 06:00.

* Address second review pass on #1493

- ReplacementDetector: canonicalize account_type in one place so filtering
  (supported_type?) and matching (type_matches?) agree on "credit card"
  vs "credit_card" variants.
- ReplacementDetector: skip candidates with nil current_balance. nil is
  "unknown," not "zero" — previously fell back to 0 and passed the near-
  zero gate, allowing suggestions without balance evidence.
This commit is contained in:
LPW
2026-04-18 00:50:34 -07:00
committed by GitHub
parent b457514c31
commit 0a96bf199d
20 changed files with 1573 additions and 33 deletions

View File

@@ -1,7 +1,7 @@
class SimplefinItemsController < ApplicationController
include SimplefinItems::MapsHelper
before_action :set_simplefin_item, only: [ :show, :edit, :update, :destroy, :sync, :balances, :setup_accounts, :complete_account_setup ]
before_action :require_admin!, only: [ :new, :create, :select_existing_account, :link_existing_account, :edit, :update, :destroy, :sync, :balances, :setup_accounts, :complete_account_setup ]
before_action :set_simplefin_item, only: [ :show, :edit, :update, :destroy, :sync, :balances, :setup_accounts, :complete_account_setup, :dismiss_replacement_suggestion ]
before_action :require_admin!, only: [ :new, :create, :select_existing_account, :link_existing_account, :edit, :update, :destroy, :sync, :balances, :setup_accounts, :complete_account_setup, :dismiss_replacement_suggestion ]
def index
@simplefin_items = Current.family.simplefin_items.active.ordered
@@ -123,6 +123,28 @@ class SimplefinItemsController < ApplicationController
end
end
# Marks one replacement-suggestion as dismissed so the banner stops showing
# for that specific (dormant, active) pair. Composite key lets us suppress
# just one option if a dormant card has multiple candidates, without hiding
# the others. Dismissals are persisted on the latest sync's sync_stats; a
# fresh sync emits new suggestions with fresh dismissal state.
def dismiss_replacement_suggestion
dormant_sfa_id = params.require(:dormant_sfa_id)
active_sfa_id = params.require(:active_sfa_id)
dismissal_key = "#{dormant_sfa_id}:#{active_sfa_id}"
sync = @simplefin_item.syncs.order(created_at: :desc).first
if sync
stats = sync.sync_stats.is_a?(Hash) ? sync.sync_stats.dup : {}
dismissed = Array(stats["dismissed_replacement_suggestions"])
stats["dismissed_replacement_suggestions"] = (dismissed + [ dismissal_key ]).uniq
sync.update!(sync_stats: stats)
end
redirect_back_or_to accounts_path,
notice: t(".dismissed")
end
# Starts a balances-only sync for this SimpleFin item
def balances
# Create a Sync and enqueue it to run asynchronously with a runtime-only flag
@@ -365,9 +387,16 @@ class SimplefinItemsController < ApplicationController
@account = Current.family.accounts.find(params[:account_id])
simplefin_account = SimplefinAccount.find(params[:simplefin_account_id])
# Guard: only manual accounts can be linked (no existing provider links or legacy IDs)
if @account.account_providers.any? || @account.plaid_account_id.present? || @account.simplefin_account_id.present?
flash[:alert] = t("simplefin_items.link_existing_account.errors.only_manual")
# Cross-provider guard: we only support swapping SimpleFIN-to-SimpleFIN links
# here. If @account is linked to a different provider type (Plaid, Binance,
# etc.), require explicit unlink first so users don't silently lose
# cross-provider data. Same-provider relinks (e.g., Citi fraud replacement
# swapping to a new card sfa) are now allowed below.
has_foreign_provider = @account.account_providers
.where.not(provider_type: "SimplefinAccount").exists? ||
@account.plaid_account_id.present?
if has_foreign_provider
flash[:alert] = t("simplefin_items.link_existing_account.errors.different_provider")
if turbo_frame_request?
return render turbo_stream: Array(flash_notification_stream_items)
else
@@ -390,6 +419,18 @@ class SimplefinItemsController < ApplicationController
Account.transaction do
simplefin_account.lock!
# Detach @account's EXISTING SimpleFIN link (if any) before attaching the
# new one. This is the fraud-replacement path: user is swapping from
# sfa_old (dead card) to sfa_new (replacement). Without this, @account
# would end up with two AccountProviders and the old sfa's data would
# still flow in on every sync.
@account.account_providers.where(provider_type: "SimplefinAccount").find_each do |existing_ap|
# Skip the one we're about to (re)assign — avoid deleting what we then recreate.
next if existing_ap.provider_id == simplefin_account.id
existing_ap.destroy
end
@account.update!(simplefin_account_id: nil) if @account.simplefin_account_id.present?
# Clear legacy association if present (Account.simplefin_account_id)
if (legacy_account = simplefin_account.account)
legacy_account.update!(simplefin_account_id: nil)

View File

@@ -38,4 +38,16 @@ module SimplefinItemsHelper
parts << "#{sample}" if sample.present?
parts.join
end
# Human-friendly relative-time phrase for an activity badge. Returns nil for
# a nil input so callers can fall through to "no activity" copy.
def activity_when(time, now: Time.current)
return nil if time.blank?
days = ((now.to_i - time.to_i) / 86_400).floor
case days
when ..0 then t("simplefin_items.setup_accounts.activity.today")
when 1 then t("simplefin_items.setup_accounts.activity.yesterday")
else t("simplefin_items.setup_accounts.activity.days_ago", count: days)
end
end
end

View File

@@ -26,6 +26,13 @@ class SimplefinAccount < ApplicationRecord
linked_account || account
end
# Summary of transaction activity derived from raw_transactions_payload.
# Used by the setup UI and ReplacementDetector to distinguish live vs dormant
# accounts without re-parsing the payload at every call site.
def activity_summary
ActivitySummary.new(raw_transactions_payload)
end
# Ensure there is an AccountProvider link for this SimpleFin account and its current Account.
# Safe and idempotent; returns the AccountProvider or nil if no account is associated yet.
def ensure_account_provider!

View File

@@ -0,0 +1,67 @@
class SimplefinAccount
# Value object summarising the activity state of a SimpleFIN account's raw
# transactions payload. Used by the setup UI to help users distinguish live
# from dormant accounts, and by the ReplacementDetector to spot cards that
# have likely been replaced.
class ActivitySummary
DEFAULT_WINDOW_DAYS = 60
def initialize(transactions)
@transactions = Array(transactions).compact
end
def last_transacted_at
return @last_transacted_at if defined?(@last_transacted_at)
@last_transacted_at = @transactions.filter_map { |tx| transacted_at(tx) }.max
end
def days_since_last_activity(now: Time.current)
return nil unless last_transacted_at
((now.to_i - last_transacted_at.to_i) / 86_400).floor
end
def recent_transaction_count(days: DEFAULT_WINDOW_DAYS)
cutoff = days.days.ago
@transactions.count { |tx| (ts = transacted_at(tx)) && ts >= cutoff }
end
def recently_active?(days: DEFAULT_WINDOW_DAYS)
recent_transaction_count(days: days).positive?
end
def dormant?(days: DEFAULT_WINDOW_DAYS)
!recently_active?(days: days)
end
def transaction_count
@transactions.size
end
private
# Extract a Time for sorting/windowing. Prefer transacted_at (SimpleFIN
# authored timestamp), fall back to posted. Zero values mean "unknown"
# in SimpleFIN (e.g., pending transactions have posted=0) and are ignored.
# Note: integer 0 is truthy in Ruby, so a plain `|| fallback` short-circuits
# and never falls back. Use explicit helper so transacted_at=0 properly
# yields to posted.
def transacted_at(tx)
return nil unless tx.is_a?(Hash) || tx.respond_to?(:[])
value = timestamp_value(fetch(tx, "transacted_at")) ||
timestamp_value(fetch(tx, "posted"))
return nil unless value
Time.at(value)
rescue StandardError
nil
end
def timestamp_value(raw)
return nil if raw.blank?
value = raw.to_i
value.zero? ? nil : value
end
def fetch(tx, key)
tx[key] || tx[key.to_sym]
end
end
end

View File

@@ -50,6 +50,10 @@ class SimplefinItem::Importer
# This allows the item to recover automatically when a bank's auth issue is resolved
# in SimpleFIN Bridge, without requiring the user to manually reconnect.
maybe_clear_requires_update_status
# Detect likely card-replacement scenarios (e.g., fraud replacement).
# Persist suggestions on sync_stats so the UI can render a relink prompt.
detect_replacement_candidates
rescue RateLimitedError => e
stats["rate_limited"] = true
stats["rate_limited_at"] = Time.current.iso8601
@@ -326,6 +330,29 @@ class SimplefinItem::Importer
sync.update_columns(sync_stats: merged) # avoid callbacks/validations during tight loops
end
# Run the replacement detector on the current simplefin_item and stash
# suggestions on sync_stats for the UI to render. The detector is best-
# effort; any error is logged but never fails the whole sync.
def detect_replacement_candidates
suggestions = SimplefinItem::ReplacementDetector.new(simplefin_item).call
return if suggestions.empty?
stats["replacement_suggestions"] = suggestions
persist_stats!
Rails.logger.info(
"SimpleFIN: detected #{suggestions.size} replacement suggestion(s) for item ##{simplefin_item.id}"
)
ActiveSupport::Notifications.instrument(
"simplefin.replacement_suggestions",
item_id: simplefin_item.id,
count: suggestions.size
)
rescue => e
Rails.logger.warn(
"SimpleFIN: replacement detector failed for item ##{simplefin_item.id}: #{e.class} - #{e.message}"
)
end
# Reset status to good if no auth errors occurred in this sync.
# This allows automatic recovery when a bank's auth issue is resolved in SimpleFIN Bridge.
def maybe_clear_requires_update_status
@@ -937,33 +964,17 @@ class SimplefinItem::Importer
# Record non-fatal provider errors into sync stats without raising, so the
# rest of the accounts can continue to import. This is used when the
# response contains both :accounts and :errors.
#
# NOTE: per-institution partial errors (e.g. one bank's auth expired inside
# a SimpleFIN Bridge connection that spans many institutions) are recorded
# for observability but must NOT flip the whole simplefin_item to
# requires_update - that would block sync for every other institution on
# the same connection. The top-level handle_errors path is the correct
# place to flag the item when the SimpleFIN token itself is dead.
def record_errors(errors)
arr = Array(errors)
return if arr.empty?
# Determine if these errors indicate the item needs an update (e.g. 2FA)
needs_update = arr.any? do |error|
if error.is_a?(String)
down = error.downcase
down.include?("reauth") || down.include?("auth") || down.include?("two-factor") || down.include?("2fa") || down.include?("forbidden") || down.include?("unauthorized")
else
code = error[:code].to_s.downcase
type = error[:type].to_s.downcase
code.include?("auth") || code.include?("token") || type.include?("auth")
end
end
if needs_update
Rails.logger.warn("SimpleFin: marking item ##{simplefin_item.id} requires_update due to auth-related provider errors")
simplefin_item.update!(status: :requires_update)
ActiveSupport::Notifications.instrument(
"simplefin.item_requires_update",
item_id: simplefin_item.id,
reason: "provider_errors_partial",
count: arr.size
)
end
Rails.logger.info("SimpleFin: recording #{arr.size} non-fatal provider error(s) with partial data present")
ActiveSupport::Notifications.instrument(
"simplefin.provider_errors",

View File

@@ -0,0 +1,135 @@
class SimplefinItem
# Detects cases where a linked SimpleFIN account looks like it has been
# replaced by a new unlinked SimpleFIN account at the same institution
# (typical for credit-card fraud replacement: the bank closes the old card
# and issues a new one, so SimpleFIN returns both for a transition window).
#
# Heuristic:
# * dormant_sfa: linked to a Sure account, no activity in 45+ days,
# AND near-zero current balance.
# * active_sfa: unlinked, recently active (transactions in last 30 days),
# belongs to the same simplefin_item,
# same account_type and same organisation name as dormant_sfa.
# * pair: exactly one active_sfa matches. Two or more candidates
# are considered ambiguous and skipped to avoid a wrong
# auto-suggestion.
#
# The detector does NOT mutate any records. It returns a plain array of
# suggestion hashes which the caller (Importer) persists on sync_stats so
# the UI can render a prompt.
class ReplacementDetector
DORMANCY_DAYS = 45
ACTIVE_WINDOW_DAYS = 30
NEAR_ZERO_BALANCE = BigDecimal("1.00")
# Fraud-replacement is overwhelmingly a credit-card pattern (old card closed,
# new card issued with same institution/metadata). Checking/savings-account
# replacement exists but has very different UX cues (e.g., users get a new
# account number in advance). Scope narrowly for now; broaden later with
# account-type-aware copy if demand materialises.
SUPPORTED_ACCOUNT_TYPES = %w[credit credit_card creditcard].freeze
def initialize(simplefin_item)
@simplefin_item = simplefin_item
end
# @return [Array<Hash>] suggestions. Empty when no replacements detected.
def call
sfas = @simplefin_item.simplefin_accounts
.includes(:linked_account, :account)
.to_a
.select { |sfa| supported_type?(sfa) }
active_unlinked = sfas.select { |sfa| unlinked?(sfa) && active?(sfa) }
return [] if active_unlinked.empty?
# First pass: for each dormant candidate, find unambiguous matching actives
# (exactly one). Rejects "one dormant → many actives" collisions.
candidates = sfas.filter_map do |dormant|
next unless linked?(dormant) && dormant_with_zero_balance?(dormant)
matches = active_unlinked.select { |sfa| same_institution_and_type?(dormant, sfa) }
next if matches.size != 1
[ dormant, matches.first ]
end
# Second pass: reject "many dormants → one active" collisions. If two
# dormant accounts both claim the same active, we can't safely auto-suggest
# either — relinking both would move the provider away from the first.
active_counts = candidates.each_with_object(Hash.new(0)) { |(_d, a), h| h[a.id] += 1 }
candidates.filter_map do |dormant, active|
next if active_counts[active.id] > 1
build_suggestion(dormant: dormant, active: active)
end
end
private
def supported_type?(sfa)
SUPPORTED_ACCOUNT_TYPES.include?(canonical_account_type(sfa))
end
# Canonicalize for both gating (supported_type?) and matching
# (type_matches?) so variants like "credit card" and "credit_card"
# round-trip to the same key.
def canonical_account_type(sfa)
sfa.account_type.to_s.downcase.gsub(/\s+/, "_")
end
def linked?(sfa)
sfa.current_account.present?
end
def unlinked?(sfa)
sfa.current_account.blank?
end
def dormant_with_zero_balance?(sfa)
# Require evidence of prior activity. An empty payload carries no signal
# (e.g., a brand-new card just linked) and must not trigger a replacement
# suggestion. Matches the likely-closed gate used by the setup UI.
return false if sfa.activity_summary.last_transacted_at.blank?
return false unless sfa.activity_summary.dormant?(days: DORMANCY_DAYS)
# Missing current_balance is "unknown," not "zero." Treat it as evidence
# against replacement rather than for it.
return false if sfa.current_balance.nil?
sfa.current_balance.to_d.abs <= NEAR_ZERO_BALANCE
end
def active?(sfa)
sfa.activity_summary.recently_active?(days: ACTIVE_WINDOW_DAYS)
end
def same_institution_and_type?(a, b)
type_matches?(a, b) && org_matches?(a, b)
end
def type_matches?(a, b)
canonical_account_type(a) == canonical_account_type(b)
end
# Require BOTH sides to have a non-blank org name. SimpleFIN sometimes omits
# org_data.name; "" casecmp? "" would otherwise treat unrelated accounts as
# co-institutional, producing false replacement suggestions.
def org_matches?(a, b)
name_a = org_name(a)
name_b = org_name(b)
return false if name_a.blank? || name_b.blank?
name_a.casecmp?(name_b)
end
def org_name(sfa)
name = sfa.org_data.is_a?(Hash) ? (sfa.org_data["name"] || sfa.org_data[:name]) : nil
name.to_s.strip
end
def build_suggestion(dormant:, active:)
{
"dormant_sfa_id" => dormant.id,
"active_sfa_id" => active.id,
"sure_account_id" => dormant.current_account&.id,
"institution_name" => org_name(dormant),
"dormant_account_name" => dormant.name,
"active_account_name" => active.name,
"confidence" => "high"
}
end
end
end

View File

@@ -71,6 +71,17 @@
<% if !account.linked? && %w[Depository CreditCard Investment Crypto].include?(account.accountable_type) %>
<% menu.with_item(variant: "link", text: t("accounts.account.link_provider"), href: select_provider_account_path(account), icon: "link", data: { turbo_frame: :modal }) %>
<% elsif account.linked? %>
<%# Same-provider relink (e.g., card-replacement fraud). Only surfaced for
SimpleFIN-linked accounts today; other providers can be added later. %>
<% if account.linked_to?("SimplefinAccount") %>
<% menu.with_item(
variant: "link",
text: t("accounts.account.change_simplefin_account"),
href: select_existing_account_simplefin_items_path(account_id: account.id),
icon: "arrow-left-right",
data: { turbo_frame: :modal }
) %>
<% end %>
<% menu.with_item(variant: "link", text: t("accounts.account.unlink_provider"), href: confirm_unlink_account_path(account), icon: "unlink", data: { turbo_frame: :modal }) %>
<% end %>
<% end %>

View File

@@ -0,0 +1,31 @@
<%#
Renders a one-line activity summary for a SimpleFIN account on the setup card.
Helps users distinguish live accounts from dormant ones during setup, which is
essential when an institution has replaced a card (e.g., fraud replacement)
and returns both the old (dormant) and new (active) cards for a sync cycle.
Locals:
activity - SimplefinAccount::ActivitySummary
likely_closed - Boolean (dormant AND near-zero balance)
%>
<% count = activity.recent_transaction_count %>
<% last_at = activity.last_transacted_at %>
<% if likely_closed %>
<p class="mt-1 flex items-center gap-1.5 text-xs text-warning">
<%= icon "alert-triangle", size: "sm" %>
<%= t("simplefin_items.setup_accounts.activity.likely_closed") %>
</p>
<% elsif count.positive? %>
<p class="mt-1 text-xs text-secondary">
<%= t("simplefin_items.setup_accounts.activity.recent", count: count, when: activity_when(last_at)) %>
</p>
<% elsif last_at.present? %>
<p class="mt-1 text-xs text-secondary">
<%= t("simplefin_items.setup_accounts.activity.dormant", days: activity.days_since_last_activity) %>
</p>
<% else %>
<p class="mt-1 text-xs text-secondary">
<%= t("simplefin_items.setup_accounts.activity.empty") %>
</p>
<% end %>

View File

@@ -0,0 +1,68 @@
<%# locals: (simplefin_item:, suggestions:)
Banner rendered at the top of the SimpleFIN item card when the importer
detects a likely card-replacement pair (old card + new card, same
institution, same type). "Relink" reuses the existing link_existing_account
controller action to atomically swap the AccountProvider on the linked
Sure account. "Dismiss" persists a per-(dormant_sfa_id) dismissal on the
latest sync's sync_stats so the banner stops showing for that pair.
Suggestions are also auto-suppressed once the relink has already landed. %>
<% latest_sync = simplefin_item.syncs.order(created_at: :desc).first %>
<% dismissed_ids = Array(latest_sync&.sync_stats&.dig("dismissed_replacement_suggestions")) %>
<div class="space-y-2">
<% suggestions.each do |suggestion| %>
<% old_sfa = simplefin_item.simplefin_accounts.find_by(id: suggestion["dormant_sfa_id"]) %>
<% new_sfa = simplefin_item.simplefin_accounts.find_by(id: suggestion["active_sfa_id"]) %>
<% sure_account = Current.family.accounts.find_by(id: suggestion["sure_account_id"]) %>
<% next unless old_sfa && new_sfa && sure_account %>
<%# Hide once the relink has landed: new sfa already linked to the target account. %>
<% next if new_sfa.current_account&.id == sure_account.id %>
<%# Hide if the user has dismissed this specific pair. %>
<% dismissal_key = "#{old_sfa.id}:#{new_sfa.id}" %>
<% next if dismissed_ids.include?(dismissal_key) %>
<div class="bg-yellow-50 theme-dark:bg-yellow-900/20 border border-yellow-200 theme-dark:border-yellow-800 rounded-lg p-4">
<div class="flex items-start gap-3">
<%= icon "credit-card", size: "sm", color: "warning", class: "shrink-0 mt-0.5" %>
<div class="flex-1 space-y-2">
<div class="flex items-start justify-between gap-2">
<p class="text-sm font-medium text-primary">
<%= t("simplefin_items.replacement_prompt.title",
institution: suggestion["institution_name"].presence || simplefin_item.name) %>
</p>
<%= button_to dismiss_replacement_suggestion_simplefin_item_path(simplefin_item),
params: { dormant_sfa_id: old_sfa.id, active_sfa_id: new_sfa.id },
method: :post,
form: { class: "inline shrink-0" },
class: "-mt-1 -mr-1 p-1 rounded hover:bg-yellow-100 theme-dark:hover:bg-yellow-900/40 text-secondary",
aria: { label: t("simplefin_items.replacement_prompt.dismiss_aria") } do %>
<%= icon "x", size: "sm" %>
<% end %>
</div>
<p class="text-xs text-secondary">
<%= t("simplefin_items.replacement_prompt.description",
account_name: sure_account.name,
old_name: old_sfa.name,
new_name: new_sfa.name) %>
</p>
<div class="pt-1">
<% confirm = CustomConfirm.new(
title: t("simplefin_items.replacement_prompt.confirm_title"),
body: t("simplefin_items.replacement_prompt.confirm_body",
account_name: sure_account.name,
new_name: new_sfa.name),
btn_text: t("simplefin_items.replacement_prompt.relink")
) %>
<%= button_to t("simplefin_items.replacement_prompt.relink"),
link_existing_account_simplefin_items_path(
account_id: sure_account.id,
simplefin_account_id: new_sfa.id
),
method: :post,
data: { turbo_confirm: confirm.to_data_attribute },
class: "inline-flex items-center gap-1.5 text-sm font-medium px-3 py-2 rounded-lg text-inverse bg-inverse hover:bg-inverse-hover" %>
</div>
</div>
</div>
</div>
<% end %>
</div>

View File

@@ -187,6 +187,15 @@
<% unless simplefin_item.scheduled_for_deletion? %>
<div class="space-y-4 mt-4">
<%# Replacement suggestions from the ReplacementDetector (card-fraud swap, etc.).
Only rendered when the latest sync flagged candidate pairs. %>
<% suggestions = ((@simplefin_sync_stats_map || {})[simplefin_item.id] || {})["replacement_suggestions"] %>
<% if suggestions.is_a?(Array) && suggestions.any? %>
<%= render "simplefin_items/replacement_prompt",
simplefin_item: simplefin_item,
suggestions: suggestions %>
<% end %>
<% if simplefin_item.accounts.any? %>
<%= render "accounts/index/account_groups", accounts: simplefin_item.accounts %>
<% end %>

View File

@@ -58,23 +58,43 @@
<% @simplefin_accounts.each do |simplefin_account| %>
<% inferred = @inferred_map[simplefin_account.id] || {} %>
<% selected_type = inferred[:confidence] == :high ? inferred[:type] : "skip" %>
<% activity = simplefin_account.activity_summary %>
<% near_zero_balance = (simplefin_account.current_balance || 0).to_d.abs <= 1 %>
<%# "Likely closed" requires evidence of prior activity that has since stopped.
An empty payload carries no signal (could be a brand-new card) so it renders
the neutral "no transactions imported yet" badge instead. %>
<% likely_closed = activity.last_transacted_at.present? && activity.dormant? && near_zero_balance %>
<%# Default likely-closed accounts (dormant AND near-zero balance) to "skip" so
users don't accidentally create empty Sure accounts for closed/replaced cards. %>
<% selected_type = if likely_closed
"skip"
else
inferred[:confidence] == :high ? inferred[:type] : "skip"
end %>
<%# Check if this account needs user attention (type selected but subtype missing) %>
<% types_with_subtypes = %w[Depository Investment Loan] %>
<% needs_subtype_attention = selected_type != "skip" && types_with_subtypes.include?(selected_type) && inferred[:subtype].blank? %>
<div class="rounded-lg p-4 <%= needs_subtype_attention ? "border-2 border-warning bg-warning/5" : "border border-primary" %>">
<% card_class = if needs_subtype_attention
"border-2 border-warning bg-warning/5"
elsif likely_closed
"border border-secondary/40 bg-surface-inset/30"
else
"border border-primary"
end %>
<div class="rounded-lg p-4 <%= card_class %>">
<div class="flex items-center justify-between mb-3">
<div>
<h3 class="font-medium text-primary">
<div class="flex-1">
<h3 class="font-medium <%= likely_closed ? "text-secondary" : "text-primary" %>">
<%= simplefin_account.name %>
<% if simplefin_account.org_data.present? && simplefin_account.org_data['name'].present? %>
<span class="text-secondary">• <%= simplefin_account.org_data["name"] %></span>
<% end %>
</h3>
<p class="text-sm text-secondary">
Balance: <%= number_to_currency(simplefin_account.current_balance || 0, unit: simplefin_account.currency) %>
<%= t(".account_card.balance") %>: <%= number_to_currency(simplefin_account.current_balance || 0, unit: simplefin_account.currency) %>
</p>
<%= render "activity_badge", activity: activity, likely_closed: likely_closed %>
</div>
</div>

View File

@@ -7,6 +7,7 @@ en:
link_lunchflow: Link with Lunch Flow
link_provider: Link with provider
unlink_provider: Unlink from provider
change_simplefin_account: Change SimpleFIN account
troubleshoot: Troubleshoot
enable: Enable account
disable: Disable account

View File

@@ -31,6 +31,20 @@ en:
placeholder: "Paste your SimpleFIN setup token here..."
help_text: "The token should be a long string starting with letters and numbers"
setup_accounts:
account_card:
balance: "Balance"
activity:
recent:
one: "1 transaction • latest %{when}"
other: "%{count} transactions • latest %{when}"
dormant: "No activity in %{days} days"
empty: "No transactions imported yet"
likely_closed: "No recent activity and zero balance — this may be a closed or replaced card"
today: "today"
yesterday: "yesterday"
days_ago:
one: "1 day ago"
other: "%{count} days ago"
stale_accounts:
title: "Accounts No Longer in SimpleFIN"
description: "These accounts exist in your database but are no longer provided by SimpleFIN. This can happen when account configurations change upstream."
@@ -97,7 +111,17 @@ en:
success: Account successfully linked to SimpleFIN
errors:
only_manual: Only manual accounts can be linked
different_provider: This account is linked to a different provider. Unlink it from that provider first, then link to SimpleFIN.
invalid_simplefin_account: Invalid SimpleFIN account selected
dismiss_replacement_suggestion:
dismissed: Replacement suggestion dismissed
replacement_prompt:
title: "Your %{institution} card may have been replaced"
description: "“%{account_name}” is linked to “%{old_name}”, which has had no recent activity and a zero balance. A new card, “%{new_name}”, is now active at the same institution. Relink to keep your history intact."
relink: Relink to new card
confirm_title: Relink to the new card?
confirm_body: "“%{account_name}” will be linked to “%{new_name}”. Your transaction history stays; future transactions come from the new card."
dismiss_aria: Dismiss replacement suggestion
reconciled_status:
message:
one: "%{count} duplicate pending transaction reconciled"

View File

@@ -490,6 +490,7 @@ Rails.application.routes.draw do
post :balances
get :setup_accounts
post :complete_account_setup
post :dismiss_replacement_suggestion
end
end

View File

@@ -0,0 +1,129 @@
# Developer utilities for exercising the SimpleFIN setup/relink flows.
# Safe only against development/test databases — never run against production.
namespace :simplefin do
desc "Seed a card-replacement (fraud) scenario for the user with the given email"
task :seed_fraud_scenario, [ :user_email ] => :environment do |_t, args|
if Rails.env.production?
abort("Refusing to run simplefin:seed_fraud_scenario in production")
end
email = args[:user_email].presence ||
ENV["USER_EMAIL"].presence ||
abort("Usage: bin/rails 'simplefin:seed_fraud_scenario[user@example.com]'")
user = User.find_by!(email: email)
family = user.family
puts "Seeding fraud scenario for #{user.email} (family: #{family.id})"
# Piggyback on an existing SimpleFIN item when the family already has one,
# so the seeded pair renders inside that card (matching how real fraud
# replacements appear: both cards come from the same institution's item).
# Fall back to a dedicated seed item otherwise.
item = family.simplefin_items.where.not(name: "Dev Fraud Scenario").first
if item
puts " Attaching to existing item: #{item.name} (#{item.id})"
else
item = family.simplefin_items.create!(
name: "Dev Fraud Scenario",
access_url: "https://example.com/seed/#{SecureRandom.hex(4)}"
)
puts " Created standalone item: #{item.name} (#{item.id})"
end
old_sfa = item.simplefin_accounts.create!(
name: "Citi Double Cash Card-OLD (9999)",
account_id: "seed_citi_old_#{SecureRandom.hex(3)}",
currency: "USD",
account_type: "credit",
current_balance: 0,
org_data: { "name" => "Citibank" },
raw_transactions_payload: [
{
"id" => "seed_old_tx_1",
"transacted_at" => 60.days.ago.to_i,
"posted" => 60.days.ago.to_i,
"amount" => "-42.50",
"payee" => "Coffee Shop"
}
]
)
sure_account = family.accounts.create!(
name: "Citi Double Cash (dev seed)",
balance: 0,
currency: "USD",
accountable: CreditCard.create!(subtype: "credit_card")
)
AccountProvider.create!(account: sure_account, provider: old_sfa)
new_sfa = item.simplefin_accounts.create!(
name: "Citi Double Cash Card-NEW (1111)",
account_id: "seed_citi_new_#{SecureRandom.hex(3)}",
currency: "USD",
account_type: "credit",
current_balance: -987.65,
org_data: { "name" => "Citibank" },
raw_transactions_payload: [
{ "id" => "seed_new_tx_1", "transacted_at" => 1.day.ago.to_i, "posted" => 1.day.ago.to_i, "amount" => "-24.50", "payee" => "Lunch" },
{ "id" => "seed_new_tx_2", "transacted_at" => 3.days.ago.to_i, "posted" => 3.days.ago.to_i, "amount" => "-120.00", "payee" => "Gas Station" }
]
)
# Simulate a recent sync so the prompt path fires (sync_stats holds the suggestion).
suggestions = SimplefinItem::ReplacementDetector.new(item).call
sync = item.syncs.create!(
status: :completed,
sync_stats: { "replacement_suggestions" => suggestions }
)
sync.update_column(:created_at, Time.current)
puts "Created:"
puts " SimplefinItem: #{item.id}"
puts " Dormant sfa (OLD): #{old_sfa.id}"
puts " Active sfa (NEW): #{new_sfa.id}"
puts " Sure account: #{sure_account.id}"
puts " Suggestions: #{suggestions.size}"
puts
puts "Next: load the accounts page in the dev server. You should see a"
puts "replacement prompt on the 'Dev Fraud Scenario' SimpleFIN card."
puts
puts "To tear down: bin/rails 'simplefin:cleanup_fraud_scenario[#{email}]'"
end
desc "Remove all seeded fraud scenarios for the given user"
task :cleanup_fraud_scenario, [ :user_email ] => :environment do |_t, args|
if Rails.env.production?
abort("Refusing to run simplefin:cleanup_fraud_scenario in production")
end
email = args[:user_email].presence ||
ENV["USER_EMAIL"].presence ||
abort("Usage: bin/rails 'simplefin:cleanup_fraud_scenario[user@example.com]'")
user = User.find_by!(email: email)
family = user.family
# Drop seeded sfas by account_id prefix (see seed_* values in the seed task)
# plus the Sure account created by the seed. This handles both the
# standalone-item path and the piggyback-on-existing-item path.
seed_sfas = SimplefinAccount
.joins(:simplefin_item)
.where(simplefin_items: { family_id: family.id })
.where("account_id LIKE ?", "seed_citi_%")
count_sfas = seed_sfas.count
seed_sfas.find_each do |sfa|
acct = sfa.current_account
AccountProvider.where(provider: sfa).destroy_all
acct&.destroy_later if acct&.may_mark_for_deletion?
sfa.destroy
end
# Drop the seeded Sure account even when unlinked (name-based, safe).
family.accounts.where(name: "Citi Double Cash (dev seed)").find_each do |acct|
acct.destroy_later if acct.may_mark_for_deletion?
end
# Drop the standalone fallback item if it has no other sfas.
family.simplefin_items.where(name: "Dev Fraud Scenario").find_each do |item|
item.destroy if item.simplefin_accounts.reload.empty?
end
puts "Removed #{count_sfas} seeded sfa(s) for #{user.email}"
end
end

View File

@@ -476,6 +476,383 @@ class SimplefinItemsControllerTest < ActionDispatch::IntegrationTest
assert !q.key?("open_relink_for"), "did not expect auto-open when update produced no SFAs/candidates"
end
# Replacement detection prompt (surfaces on the SimpleFIN card when the
# importer's ReplacementDetector has persisted suggestions on sync_stats).
test "replacement prompt renders on accounts index when suggestions are persisted" do
# Create the two sfas the detector would flag
old_sfa = @simplefin_item.simplefin_accounts.create!(
name: "Citi-3831", account_id: "sf_3831",
currency: "USD", account_type: "credit", current_balance: 0,
org_data: { "name" => "Citibank" },
raw_transactions_payload: [
{ "id" => "t", "transacted_at" => 90.days.ago.to_i, "posted" => 90.days.ago.to_i, "amount" => "-5" }
]
)
sure_account = Account.create!(
family: @family,
name: "Citi Double Cash Card-3831",
balance: 0, currency: "USD",
accountable: CreditCard.create!(subtype: "credit_card")
)
AccountProvider.create!(account: sure_account, provider: old_sfa)
new_sfa = @simplefin_item.simplefin_accounts.create!(
name: "Citi-2879", account_id: "sf_2879",
currency: "USD", account_type: "credit", current_balance: -1200,
org_data: { "name" => "Citibank" },
raw_transactions_payload: [
{ "id" => "n", "transacted_at" => 2.days.ago.to_i, "posted" => 2.days.ago.to_i, "amount" => "-100" }
]
)
# Persist a suggestion on the latest sync
sync = @simplefin_item.syncs.create!(status: :completed, sync_stats: {
"replacement_suggestions" => [
{
"dormant_sfa_id" => old_sfa.id,
"active_sfa_id" => new_sfa.id,
"sure_account_id" => sure_account.id,
"institution_name" => "Citibank",
"dormant_account_name" => "Citi-3831",
"active_account_name" => "Citi-2879",
"confidence" => "high"
}
]
})
sync.update_column(:created_at, Time.current)
get accounts_url
assert_response :success
assert_match(/Citibank card may have been replaced/, response.body)
assert_match(/Citi Double Cash Card-3831/, response.body)
assert_match(/Relink to new card/, response.body)
end
test "replacement prompt is suppressed once the relink has been applied" do
old_sfa = @simplefin_item.simplefin_accounts.create!(
name: "Citi-3831", account_id: "sf_3831_applied",
currency: "USD", account_type: "credit", current_balance: 0,
org_data: { "name" => "Citibank" },
raw_transactions_payload: [
{ "id" => "t", "transacted_at" => 90.days.ago.to_i, "posted" => 90.days.ago.to_i, "amount" => "-5" }
]
)
sure_account = Account.create!(
family: @family,
name: "Citi Double Cash Card-3831 (applied)",
balance: 0, currency: "USD",
accountable: CreditCard.create!(subtype: "credit_card")
)
new_sfa = @simplefin_item.simplefin_accounts.create!(
name: "Citi-2879", account_id: "sf_2879_applied",
currency: "USD", account_type: "credit", current_balance: -1200,
org_data: { "name" => "Citibank" },
raw_transactions_payload: [
{ "id" => "n", "transacted_at" => 2.days.ago.to_i, "posted" => 2.days.ago.to_i, "amount" => "-100" }
]
)
# Simulate the post-relink state: new_sfa is now linked to the Sure account,
# old_sfa is unlinked. sync_stats still carries the stale suggestion.
AccountProvider.create!(account: sure_account, provider: new_sfa)
sync = @simplefin_item.syncs.create!(status: :completed, sync_stats: {
"replacement_suggestions" => [
{
"dormant_sfa_id" => old_sfa.id,
"active_sfa_id" => new_sfa.id,
"sure_account_id" => sure_account.id,
"institution_name" => "Citibank",
"dormant_account_name" => "Citi-3831",
"active_account_name" => "Citi-2879",
"confidence" => "high"
}
]
})
sync.update_column(:created_at, Time.current)
get accounts_url
assert_response :success
refute_match(/Citibank card may have been replaced/, response.body,
"banner should disappear once the relink has landed on the new sfa")
end
test "dismissing a replacement suggestion hides the banner for that pair" do
old_sfa = @simplefin_item.simplefin_accounts.create!(
name: "Citi-3831", account_id: "sf_3831_dismiss",
currency: "USD", account_type: "credit", current_balance: 0,
org_data: { "name" => "Citibank" },
raw_transactions_payload: [
{ "id" => "t", "transacted_at" => 90.days.ago.to_i, "posted" => 90.days.ago.to_i, "amount" => "-5" }
]
)
sure_account = Account.create!(
family: @family, name: "Citi Double Cash Card-3831 (dismiss)",
balance: 0, currency: "USD",
accountable: CreditCard.create!(subtype: "credit_card")
)
AccountProvider.create!(account: sure_account, provider: old_sfa)
new_sfa = @simplefin_item.simplefin_accounts.create!(
name: "Citi-2879", account_id: "sf_2879_dismiss",
currency: "USD", account_type: "credit", current_balance: -1200,
org_data: { "name" => "Citibank" },
raw_transactions_payload: [
{ "id" => "n", "transacted_at" => 2.days.ago.to_i, "posted" => 2.days.ago.to_i, "amount" => "-100" }
]
)
sync = @simplefin_item.syncs.create!(status: :completed, sync_stats: {
"replacement_suggestions" => [
{
"dormant_sfa_id" => old_sfa.id,
"active_sfa_id" => new_sfa.id,
"sure_account_id" => sure_account.id,
"institution_name" => "Citibank",
"confidence" => "high"
}
]
})
sync.update_column(:created_at, Time.current)
# Banner is present before dismissal
get accounts_url
assert_match(/Citibank card may have been replaced/, response.body)
# Dismiss — pair key (dormant + active)
post dismiss_replacement_suggestion_simplefin_item_path(@simplefin_item), params: {
dormant_sfa_id: old_sfa.id,
active_sfa_id: new_sfa.id
}
sync.reload
assert_includes Array(sync.sync_stats["dismissed_replacement_suggestions"]),
"#{old_sfa.id}:#{new_sfa.id}"
# Banner is gone after dismissal
get accounts_url
refute_match(/Citibank card may have been replaced/, response.body,
"banner should not render for a dismissed pair")
end
test "replacement prompt relink button successfully swaps AccountProvider" do
old_sfa = @simplefin_item.simplefin_accounts.create!(
name: "Old", account_id: "o1", currency: "USD",
account_type: "credit", current_balance: 0
)
new_sfa = @simplefin_item.simplefin_accounts.create!(
name: "New", account_id: "n1", currency: "USD",
account_type: "credit", current_balance: -500
)
sure_account = Account.create!(
family: @family, name: "Citi", balance: 0, currency: "USD",
accountable: CreditCard.create!(subtype: "credit_card")
)
AccountProvider.create!(account: sure_account, provider: old_sfa)
# The relink button posts to link_existing_account just like the modal does
post link_existing_account_simplefin_items_path, params: {
account_id: sure_account.id,
simplefin_account_id: new_sfa.id
}
sure_account.reload
sf_aps = sure_account.account_providers.where(provider_type: "SimplefinAccount")
assert_equal 1, sf_aps.count
assert_equal new_sfa.id, sf_aps.first.provider_id
end
# Same-provider relink tests (Bug #3 — allow SimpleFIN-to-SimpleFIN swap without unlink dance)
test "link_existing_account allows relink when account is already SimpleFIN-linked via AccountProvider" do
# @account currently linked to sfa_old (fraud-replaced card). User picks sfa_new.
account = Account.create!(
family: @family,
name: "Citi Double Cash",
balance: 0,
currency: "USD",
accountable: CreditCard.create!(subtype: "credit_card")
)
sfa_old = @simplefin_item.simplefin_accounts.create!(
name: "Citi Card-OLD",
account_id: "sf_citi_old",
currency: "USD",
account_type: "credit",
current_balance: 0
)
sfa_new = @simplefin_item.simplefin_accounts.create!(
name: "Citi Card-NEW",
account_id: "sf_citi_new",
currency: "USD",
account_type: "credit",
current_balance: -100
)
AccountProvider.create!(account: account, provider: sfa_old)
post link_existing_account_simplefin_items_path, params: {
account_id: account.id,
simplefin_account_id: sfa_new.id
}
assert_response :see_other
# The SimpleFIN link should now point at sfa_new
account.reload
sf_providers = account.account_providers.where(provider_type: "SimplefinAccount")
assert_equal 1, sf_providers.count, "should have exactly one SimpleFIN link after relink"
assert_equal sfa_new.id, sf_providers.first.provider_id
# Old AccountProvider for sfa_old on this account is detached
refute AccountProvider.exists?(account_id: account.id, provider: sfa_old),
"old SimpleFIN AccountProvider for this account should be detached"
end
test "link_existing_account allows relink when account has only legacy simplefin_account_id FK" do
account = Account.create!(
family: @family,
name: "Citi Double Cash",
balance: 0,
currency: "USD",
accountable: CreditCard.create!(subtype: "credit_card")
)
sfa_old = @simplefin_item.simplefin_accounts.create!(
name: "Citi Card-OLD",
account_id: "sf_citi_old2",
currency: "USD",
account_type: "credit",
current_balance: 0
)
sfa_new = @simplefin_item.simplefin_accounts.create!(
name: "Citi Card-NEW",
account_id: "sf_citi_new2",
currency: "USD",
account_type: "credit",
current_balance: -100
)
account.update!(simplefin_account_id: sfa_old.id)
post link_existing_account_simplefin_items_path, params: {
account_id: account.id,
simplefin_account_id: sfa_new.id
}
assert_response :see_other
account.reload
assert_nil account.simplefin_account_id, "legacy SimpleFIN FK should be cleared"
assert_equal sfa_new.id,
account.account_providers.where(provider_type: "SimplefinAccount").first&.provider_id
end
test "link_existing_account rejects when account is linked to a foreign provider (Plaid)" do
account = Account.create!(
family: @family,
name: "Plaid-Linked",
balance: 0,
currency: "USD",
accountable: Depository.create!(subtype: "checking")
)
plaid_item = PlaidItem.create!(family: @family, name: "Plaid Conn", access_token: "t", plaid_id: "p")
plaid_acct = PlaidAccount.create!(
plaid_item: plaid_item,
plaid_id: "p_acct_1",
name: "Plaid A",
plaid_type: "depository",
currency: "USD",
current_balance: 0
)
AccountProvider.create!(account: account, provider: plaid_acct)
sfa = @simplefin_item.simplefin_accounts.create!(
name: "SF-Target",
account_id: "sf_target_1",
currency: "USD",
account_type: "depository",
current_balance: 100
)
post link_existing_account_simplefin_items_path, params: {
account_id: account.id,
simplefin_account_id: sfa.id
}
# Should NOT have attached the SimpleFIN provider
account.reload
assert_empty account.account_providers.where(provider_type: "SimplefinAccount")
# Plaid link should remain intact
assert account.account_providers.where(provider_type: "PlaidAccount").exists?
end
# Activity badge tests (helps users distinguish live vs replaced/closed cards during setup)
test "setup_accounts renders recent-transactions badge for active sfa" do
@simplefin_item.simplefin_accounts.create!(
name: "Active Card",
account_id: "active_card_1",
currency: "USD",
account_type: "credit",
current_balance: -123.45,
raw_transactions_payload: [
{ "id" => "t1", "transacted_at" => 3.days.ago.to_i, "posted" => 3.days.ago.to_i, "amount" => "-10" },
{ "id" => "t2", "transacted_at" => 10.days.ago.to_i, "posted" => 10.days.ago.to_i, "amount" => "-20" }
]
)
get setup_accounts_simplefin_item_url(@simplefin_item)
assert_response :success
assert_match(/2 transactions.*3 days ago/, response.body,
"expected active sfa to show recent transaction count and last activity")
end
test "setup_accounts renders 'likely closed' warning for dormant+zero-balance sfa" do
@simplefin_item.simplefin_accounts.create!(
name: "Dead Card",
account_id: "dead_card_1",
currency: "USD",
account_type: "credit",
current_balance: 0,
raw_transactions_payload: [
{ "id" => "old", "transacted_at" => 120.days.ago.to_i, "posted" => 120.days.ago.to_i, "amount" => "-5" }
]
)
get setup_accounts_simplefin_item_url(@simplefin_item)
assert_response :success
assert_match(/closed or replaced card/, response.body,
"expected dormant+zero-balance sfa to show closed/replaced warning")
end
test "setup_accounts renders 'no transactions imported' for empty sfa" do
@simplefin_item.simplefin_accounts.create!(
name: "Brand New Card",
account_id: "fresh_card_1",
currency: "USD",
account_type: "credit",
current_balance: 0,
raw_transactions_payload: []
)
get setup_accounts_simplefin_item_url(@simplefin_item)
assert_response :success
assert_match(/No transactions imported yet/, response.body)
end
test "setup_accounts renders 'dormant but has balance' as plain text not warning" do
# Legitimate dormant case: HSA/savings account with real balance but no recent activity.
# Should NOT be flagged as likely-closed because the balance is non-trivial.
@simplefin_item.simplefin_accounts.create!(
name: "Dormant HSA",
account_id: "dormant_hsa_1",
currency: "USD",
account_type: "investment",
current_balance: 5432.10,
raw_transactions_payload: [
{ "id" => "old", "transacted_at" => 120.days.ago.to_i, "posted" => 120.days.ago.to_i, "amount" => "100" }
]
)
get setup_accounts_simplefin_item_url(@simplefin_item)
assert_response :success
assert_match(/No activity in 120 days/, response.body)
refute_match(/closed or replaced card/, response.body,
"dormant accounts with real balances should not be marked as closed")
end
# Stale account detection and handling tests
test "setup_accounts detects stale accounts not in upstream API" do

View File

@@ -0,0 +1,62 @@
require "test_helper"
class SimplefinItemsHelperTest < ActionView::TestCase
test "#activity_when returns nil for blank time" do
assert_nil activity_when(nil)
assert_nil activity_when("")
end
test "#activity_when returns 'today' for current time" do
assert_equal "today", activity_when(Time.current)
end
test "#activity_when returns 'today' for earlier today" do
# Freeze at mid-day so 6.hours.ago is guaranteed to fall on the same
# calendar day regardless of when the suite runs.
travel_to(Time.zone.parse("2026-04-17 15:00:00")) do
assert_equal "today", activity_when(6.hours.ago)
end
end
test "#activity_when returns 'yesterday' one day back" do
assert_equal "yesterday", activity_when(1.day.ago)
end
test "#activity_when returns 'N days ago' for older dates" do
# Freeze time so relative "N days ago" stays stable regardless of the
# hour-of-day the suite runs.
travel_to(Time.zone.parse("2026-04-17 15:00:00")) do
assert_equal "5 days ago", activity_when(5.days.ago)
# 2 days ago is the first value that hits the plural "N days ago" branch
# (0 -> today, 1 -> yesterday, >=2 -> N days ago).
assert_equal "2 days ago", activity_when(2.days.ago)
end
end
test "#activity_when respects injected now: for deterministic formatting" do
now = Time.zone.parse("2026-04-17 12:00:00")
assert_equal "7 days ago", activity_when(now - 7.days, now: now)
end
# ---- simplefin_error_tooltip (pre-existing) ----
test "#simplefin_error_tooltip returns nil for blank stats" do
assert_nil simplefin_error_tooltip(nil)
assert_nil simplefin_error_tooltip({})
assert_nil simplefin_error_tooltip({ "total_errors" => 0 })
end
test "#simplefin_error_tooltip builds a sample with bucket counts" do
stats = {
"total_errors" => 3,
"errors" => [
{ "name" => "Chase", "message" => "Timeout" },
{ "name" => "Citi", "message" => "Auth" }
],
"error_buckets" => { "auth" => 1, "network" => 2 }
}
tooltip = simplefin_error_tooltip(stats)
assert_includes tooltip, "Errors:"
assert_includes tooltip, "3"
assert_includes tooltip, "auth: 1"
end
end

View File

@@ -0,0 +1,172 @@
require "test_helper"
class SimplefinAccount::ActivitySummaryTest < ActiveSupport::TestCase
def build(transactions)
SimplefinAccount::ActivitySummary.new(transactions)
end
def tx(date: nil, amount: -10.0, posted: nil, pending: false, payee: "Test")
{
"id" => "TRN-#{SecureRandom.hex(4)}",
"amount" => amount.to_s,
"posted" => (posted.nil? ? 0 : posted.to_i),
"pending" => pending,
"payee" => payee,
"description" => payee.upcase,
"transacted_at" => (date || Time.current).to_i
}
end
test "empty payload is dormant with nil last_transacted_at and zero counts" do
summary = build([])
assert_nil summary.last_transacted_at
assert_equal 0, summary.transaction_count
assert_equal 0, summary.recent_transaction_count
assert summary.dormant?
refute summary.recently_active?
end
test "nil payload is treated as empty" do
summary = build(nil)
assert summary.dormant?
assert_equal 0, summary.transaction_count
end
test "last_transacted_at returns the most recent transaction time" do
latest = 3.days.ago
summary = build([
tx(date: 30.days.ago),
tx(date: latest),
tx(date: 10.days.ago)
])
assert_in_delta latest.to_i, summary.last_transacted_at.to_i, 2
end
test "recent_transaction_count counts within default 60-day window" do
summary = build([
tx(date: 30.days.ago),
tx(date: 45.days.ago),
tx(date: 90.days.ago),
tx(date: 120.days.ago)
])
assert_equal 2, summary.recent_transaction_count
end
test "recent_transaction_count honors custom window" do
summary = build([
tx(date: 10.days.ago),
tx(date: 20.days.ago),
tx(date: 40.days.ago)
])
assert_equal 1, summary.recent_transaction_count(days: 15)
assert_equal 3, summary.recent_transaction_count(days: 90)
end
test "falls back to posted when transacted_at is zero (unknown)" do
# SimpleFIN uses 0 to signal "unknown" for transacted_at. Because 0 is
# truthy in Ruby, a naive `transacted_at || posted` short-circuits to 0
# and never falls back. Verify the fallback still produces the posted time.
posted_ts = 5.days.ago.to_i
summary = SimplefinAccount::ActivitySummary.new([
{ "transacted_at" => 0, "posted" => posted_ts, "amount" => "-5" }
])
assert_equal Time.at(posted_ts), summary.last_transacted_at
end
test "dormant? returns true when no activity within window" do
summary = build([ tx(date: 120.days.ago) ])
assert summary.dormant?
refute summary.recently_active?
end
test "dormant? returns false when any recent activity exists" do
summary = build([ tx(date: 120.days.ago), tx(date: 3.days.ago) ])
refute summary.dormant?
assert summary.recently_active?
end
test "days_since_last_activity returns whole days since newest tx" do
summary = build([ tx(date: 37.days.ago) ])
assert_equal 37, summary.days_since_last_activity
end
test "days_since_last_activity is nil when no transactions" do
assert_nil build([]).days_since_last_activity
end
test "ignores transactions with zero transacted_at and zero posted" do
# SimpleFIN uses posted=0 for pending; malformed entries may have transacted_at=0
summary = build([
{ "id" => "a", "transacted_at" => 0, "posted" => 0, "amount" => "-5" },
tx(date: 3.days.ago)
])
assert_in_delta 3.days.ago.to_i, summary.last_transacted_at.to_i, 2
assert_equal 1, summary.recent_transaction_count
end
test "falls back to posted when transacted_at is absent" do
posted_time = 5.days.ago.to_i
summary = build([
{ "id" => "a", "amount" => "-5", "posted" => posted_time, "pending" => false }
])
assert_in_delta posted_time, summary.last_transacted_at.to_i, 2
assert_equal 1, summary.recent_transaction_count
end
test "accepts symbol-keyed transaction hashes" do
summary = build([
{ transacted_at: 3.days.ago.to_i, amount: "-5", id: "a" },
{ "transacted_at" => 3.days.ago.to_i, "amount" => "-5", "id" => "b" }
])
assert_equal 2, summary.recent_transaction_count
end
end
class SimplefinAccountActivitySummaryIntegrationTest < ActiveSupport::TestCase
setup do
@family = families(:dylan_family)
@item = SimplefinItem.create!(
family: @family,
name: "SF Conn",
access_url: "https://example.com/access"
)
end
test "#activity_summary wraps raw_transactions_payload" do
sfa = SimplefinAccount.create!(
simplefin_item: @item,
name: "Active Card",
account_id: "sf-active",
account_type: "credit",
currency: "USD",
current_balance: -100,
raw_transactions_payload: [
{
"id" => "t1",
"amount" => "-50",
"posted" => 3.days.ago.to_i,
"transacted_at" => 3.days.ago.to_i
}
]
)
summary = sfa.activity_summary
assert_kind_of SimplefinAccount::ActivitySummary, summary
assert summary.recently_active?
assert_equal 1, summary.transaction_count
end
test "#activity_summary handles nil raw_transactions_payload" do
sfa = SimplefinAccount.create!(
simplefin_item: @item,
name: "Empty Card",
account_id: "sf-empty",
account_type: "credit",
currency: "USD",
current_balance: 0,
raw_transactions_payload: nil
)
summary = sfa.activity_summary
assert_equal 0, summary.transaction_count
assert summary.dormant?
end
end

View File

@@ -0,0 +1,103 @@
require "test_helper"
# Verifies the boundary between per-institution partial errors (which must not
# poison the whole SimpleFIN item's status) and top-level token-auth failures
# (which legitimately flag the item for reconnection).
class SimplefinItem::ImporterPartialErrorsTest < ActiveSupport::TestCase
setup do
@family = families(:dylan_family)
@item = SimplefinItem.create!(
family: @family,
name: "SF Conn",
access_url: "https://example.com/access"
)
@sync = Sync.create!(syncable: @item)
@importer = SimplefinItem::Importer.new(@item, simplefin_provider: mock(), sync: @sync)
end
test "per-institution auth error does NOT flip item to requires_update" do
# Partial-response error for ONE institution (e.g. Cash App) should not
# poison the other 8 institutions in the same SimpleFIN connection.
assert_equal "good", @item.status
@importer.send(:record_errors, [
"Connection to Cash App may need attention. Auth required"
])
@item.reload
assert_equal "good", @item.status,
"expected item to remain good; per-institution auth errors must not flip the whole connection"
end
test "per-institution auth error still tracks in error_buckets for observability" do
@importer.send(:record_errors, [
"Connection to Cash App may need attention. Auth required"
])
stats = @sync.reload.sync_stats
assert_equal 1, stats.dig("error_buckets", "auth").to_i,
"auth-category error should still be tracked in stats"
end
test "multiple per-institution errors do not flip item status" do
@importer.send(:record_errors, [
"Connection to Cash App may need attention. Auth required",
"Please reauthenticate with Citibank",
"two-factor authentication failed at Chase"
])
@item.reload
assert_equal "good", @item.status
assert_equal 3, @sync.reload.sync_stats.dig("error_buckets", "auth").to_i
end
test "hash-shaped per-institution auth error does not flip item status" do
@importer.send(:record_errors, [
{ code: "auth_failure", description: "Auth required for Cash App" }
])
@item.reload
assert_equal "good", @item.status
end
test "top-level handle_errors with auth failure DOES flip item to requires_update" do
# Distinct from record_errors: this is the token-revoked / whole-connection-dead path.
assert_equal "good", @item.status
assert_raises(Provider::Simplefin::SimplefinError) do
@importer.send(:handle_errors, [
{ code: "auth_failure", description: "Your SimpleFIN setup token was revoked" }
])
end
@item.reload
assert_equal "requires_update", @item.status,
"top-level token auth failures must still flag the item for reconnection"
end
test "previously requires_update item is cleared when no auth errors this sync" do
@item.update!(status: :requires_update)
# Simulate a clean sync (the maybe_clear path is already exercised in-suite;
# here we confirm that record_errors with zero auth errors doesn't re-flag).
@importer.send(:record_errors, [ "Timed out fetching Chase" ])
@item.reload
# record_errors alone doesn't clear - that's maybe_clear_requires_update_status's job -
# but it also must not RE-flag when the error isn't auth-related.
assert_equal "requires_update", @item.status
end
test "non-auth partial errors don't flip status" do
@importer.send(:record_errors, [
"Timed out fetching transactions from Chase",
"429 rate limit hit at Citibank"
])
@item.reload
assert_equal "good", @item.status
stats = @sync.reload.sync_stats
assert_equal 1, stats.dig("error_buckets", "network").to_i
assert_equal 1, stats.dig("error_buckets", "api").to_i
end
end

View File

@@ -0,0 +1,259 @@
require "test_helper"
class SimplefinItem::ReplacementDetectorTest < ActiveSupport::TestCase
setup do
@family = families(:dylan_family)
@item = SimplefinItem.create!(
family: @family,
name: "SF Conn",
access_url: "https://example.com/access"
)
end
def make_sfa(name:, account_id:, account_type: "credit", org_name: "Citibank",
balance: -100, transactions: [])
@item.simplefin_accounts.create!(
name: name,
account_id: account_id,
currency: "USD",
account_type: account_type,
current_balance: balance,
org_data: { "name" => org_name },
raw_transactions_payload: transactions
)
end
def link(sfa, name:)
account = @family.accounts.create!(
name: name,
balance: (sfa.current_balance || 0).to_d,
currency: sfa.currency,
accountable: CreditCard.create!(subtype: "credit_card")
)
sfa.update!(account: account)
account.update!(simplefin_account_id: sfa.id)
account
end
def tx(when_ago:)
{ "id" => SecureRandom.hex(4), "transacted_at" => when_ago.ago.to_i, "posted" => when_ago.ago.to_i, "amount" => "-5" }
end
test "returns empty when simplefin_item has no accounts" do
assert_equal [], SimplefinItem::ReplacementDetector.new(@item).call
end
test "returns empty when there are no active unlinked candidates" do
dormant = make_sfa(name: "Citi Old", account_id: "sf_old", balance: 0, transactions: [ tx(when_ago: 90.days) ])
link(dormant, name: "Citi Double Cash")
# No unlinked sfas at all
assert_equal [], SimplefinItem::ReplacementDetector.new(@item).call
end
test "detects classic fraud replacement: dormant+zero linked sfa + active unlinked sfa same org+type" do
dormant = make_sfa(name: "Citi-3831", account_id: "sf_3831", balance: 0,
transactions: [ tx(when_ago: 45.days) ])
linked_account = link(dormant, name: "Citi Double Cash Card-3831")
active = make_sfa(name: "Citi-2879", account_id: "sf_2879", balance: -1200,
transactions: [ tx(when_ago: 2.days), tx(when_ago: 5.days) ])
suggestions = SimplefinItem::ReplacementDetector.new(@item).call
assert_equal 1, suggestions.size
suggestion = suggestions.first
assert_equal dormant.id, suggestion["dormant_sfa_id"]
assert_equal active.id, suggestion["active_sfa_id"]
assert_equal linked_account.id, suggestion["sure_account_id"]
assert_equal "Citibank", suggestion["institution_name"]
assert_equal "high", suggestion["confidence"]
end
test "ignores candidates at different institutions" do
dormant = make_sfa(name: "Citi-3831", account_id: "sf_old", balance: 0,
transactions: [ tx(when_ago: 60.days) ])
link(dormant, name: "Citi Double Cash")
# Active sfa at a DIFFERENT institution - not a real replacement
make_sfa(name: "Chase-Freedom", account_id: "sf_chase", balance: -200,
org_name: "Chase",
transactions: [ tx(when_ago: 3.days) ])
assert_empty SimplefinItem::ReplacementDetector.new(@item).call
end
test "ignores candidates with different account_type" do
dormant = make_sfa(name: "Citi-3831", account_id: "sf_old",
account_type: "credit", balance: 0,
transactions: [ tx(when_ago: 60.days) ])
link(dormant, name: "Citi Double Cash")
# Active sfa at same institution but different type
make_sfa(name: "Citi Checking", account_id: "sf_checking",
account_type: "depository", balance: 500,
transactions: [ tx(when_ago: 3.days) ])
assert_empty SimplefinItem::ReplacementDetector.new(@item).call
end
test "skips ambiguous matches (multiple candidates)" do
dormant = make_sfa(name: "Citi-3831", account_id: "sf_old", balance: 0,
transactions: [ tx(when_ago: 60.days) ])
link(dormant, name: "Citi Double Cash")
# Two active unlinked Citi credit cards — can't tell which replaced it
make_sfa(name: "Citi-2879", account_id: "sf_new1", balance: -100,
transactions: [ tx(when_ago: 2.days) ])
make_sfa(name: "Citi-4567", account_id: "sf_new2", balance: -200,
transactions: [ tx(when_ago: 5.days) ])
assert_empty SimplefinItem::ReplacementDetector.new(@item).call
end
test "ignores dormant sfa with non-zero balance (probably legitimate dormant account)" do
# A savings account sitting at $5000 with no recent activity isn't
# fraud replacement — it's just a savings account
dormant = make_sfa(name: "Dormant Savings", account_id: "sf_savings",
balance: 5000, transactions: [ tx(when_ago: 60.days) ])
link(dormant, name: "Savings Account")
make_sfa(name: "Citi-2879", account_id: "sf_new", balance: -100,
transactions: [ tx(when_ago: 2.days) ])
assert_empty SimplefinItem::ReplacementDetector.new(@item).call
end
test "ignores active sfa as the 'dormant' candidate" do
# Account with both dormant-looking AND active (recent activity): not dormant
active_linked = make_sfa(name: "Citi-3831", account_id: "sf_still_active",
balance: 0, transactions: [ tx(when_ago: 3.days) ])
link(active_linked, name: "Citi Card")
make_sfa(name: "Citi-2879", account_id: "sf_candidate", balance: -100,
transactions: [ tx(when_ago: 2.days) ])
assert_empty SimplefinItem::ReplacementDetector.new(@item).call
end
test "suggestion uses case-insensitive org and type matching" do
dormant = make_sfa(name: "Citi Old", account_id: "sf_old", balance: 0,
account_type: "CREDIT", org_name: "CITIBANK",
transactions: [ tx(when_ago: 60.days) ])
link(dormant, name: "Citi Double Cash")
active = make_sfa(name: "Citi New", account_id: "sf_new", balance: -100,
account_type: "credit", org_name: "Citibank",
transactions: [ tx(when_ago: 2.days) ])
suggestions = SimplefinItem::ReplacementDetector.new(@item).call
assert_equal 1, suggestions.size
assert_equal active.id, suggestions.first["active_sfa_id"]
end
test "detects multiple independent replacements across institutions" do
# Two fraud replacements in the same sync: Citi + Chase both replaced
dormant_citi = make_sfa(name: "Citi-old", account_id: "sf_c_old", balance: 0,
transactions: [ tx(when_ago: 60.days) ])
link(dormant_citi, name: "Citi")
make_sfa(name: "Citi-new", account_id: "sf_c_new", balance: -100,
transactions: [ tx(when_ago: 3.days) ])
dormant_chase = make_sfa(name: "Chase-old", account_id: "sf_ch_old",
org_name: "Chase", balance: 0,
transactions: [ tx(when_ago: 60.days) ])
link(dormant_chase, name: "Chase")
make_sfa(name: "Chase-new", account_id: "sf_ch_new",
org_name: "Chase", balance: -200,
transactions: [ tx(when_ago: 1.day) ])
suggestions = SimplefinItem::ReplacementDetector.new(@item).call
assert_equal 2, suggestions.size
orgs = suggestions.map { |s| s["institution_name"] }.sort
assert_equal [ "Chase", "Citibank" ], orgs
end
test "ignores non-credit account types (checking, savings, investment)" do
# Fraud-replacement UX is credit-card scoped for now. A depository/checking
# pair that matches all other detector criteria must be skipped.
dormant = make_sfa(name: "Old Checking", account_id: "sf_checking_old",
account_type: "depository", org_name: "Chase", balance: 0,
transactions: [ tx(when_ago: 60.days) ])
link(dormant, name: "Old Checking")
make_sfa(name: "New Checking", account_id: "sf_checking_new",
account_type: "depository", org_name: "Chase", balance: 1234,
transactions: [ tx(when_ago: 2.days) ])
assert_empty SimplefinItem::ReplacementDetector.new(@item).call
end
test "does not emit multiple suggestions pointing at the same active sfa" do
# Two dormant credit cards at the same institution, one new active card.
# Relinking both would move the provider away from the first account.
# Detector must skip both to avoid silent breakage.
dormant1 = make_sfa(name: "Citi-OLD-1", account_id: "sf_old1", balance: 0,
transactions: [ tx(when_ago: 60.days) ])
link(dormant1, name: "Citi Card 1")
dormant2 = make_sfa(name: "Citi-OLD-2", account_id: "sf_old2", balance: 0,
transactions: [ tx(when_ago: 60.days) ])
link(dormant2, name: "Citi Card 2")
make_sfa(name: "Citi-NEW", account_id: "sf_new", balance: -100,
transactions: [ tx(when_ago: 2.days) ])
suggestions = SimplefinItem::ReplacementDetector.new(@item).call
assert_empty suggestions, "must not emit ambiguous pairs that reuse the same active sfa"
end
test "treats blank institution names as non-matching (not co-institutional)" do
# SimpleFIN sometimes omits org_data.name. Two credit-card sfas with blank
# org names must NOT be treated as at the same institution — otherwise any
# dormant+active credit pair would auto-match regardless of provider.
dormant = @item.simplefin_accounts.create!(
name: "Mystery-OLD", account_id: "sf_mystery_old",
currency: "USD", account_type: "credit", current_balance: 0,
org_data: {},
raw_transactions_payload: [ tx(when_ago: 60.days) ]
)
link(dormant, name: "Mystery")
@item.simplefin_accounts.create!(
name: "Mystery-NEW", account_id: "sf_mystery_new",
currency: "USD", account_type: "credit", current_balance: -200,
org_data: {},
raw_transactions_payload: [ tx(when_ago: 2.days) ]
)
assert_empty SimplefinItem::ReplacementDetector.new(@item).call
end
test "ignores dormant candidate when current_balance is unknown (nil)" do
# nil balance is 'unknown,' not 'zero.' Treat as evidence against a match.
# Model-level validation normally prevents nil current_balance but upstream
# data has occasionally landed this way; simulate via `update_columns` to
# bypass validation and assert the detector's robustness.
dormant = make_sfa(name: "Citi-UNKNOWN-BAL", account_id: "sf_nil_bal",
balance: 0, transactions: [ tx(when_ago: 60.days) ])
link(dormant, name: "Unknown Citi")
dormant.update_columns(current_balance: nil, available_balance: nil)
make_sfa(name: "New Citi", account_id: "sf_nil_new", balance: -100,
transactions: [ tx(when_ago: 2.days) ])
assert_empty SimplefinItem::ReplacementDetector.new(@item).call
end
test "matches sfa pairs when account_type uses 'credit card' / 'credit_card' variants" do
dormant = make_sfa(name: "Citi-OLD-var", account_id: "sf_var_old",
account_type: "credit card", balance: 0,
transactions: [ tx(when_ago: 60.days) ])
link(dormant, name: "Variant Citi")
make_sfa(name: "Citi-NEW-var", account_id: "sf_var_new",
account_type: "credit_card", balance: -100,
transactions: [ tx(when_ago: 2.days) ])
suggestions = SimplefinItem::ReplacementDetector.new(@item).call
assert_equal 1, suggestions.size, "canonicalized account_type should match across spacing variants"
end
test "ignores linked sfa with no transaction history (brand-new card, not dormant)" do
# A newly linked card with zero balance and no transactions yet must NOT be
# flagged as a replacement target. "Dormant" requires prior activity that
# has since gone silent; an empty payload carries no such signal.
fresh = make_sfa(name: "Brand New Citi", account_id: "sf_fresh", balance: 0, transactions: [])
link(fresh, name: "Brand New Citi Card")
make_sfa(name: "Other Citi", account_id: "sf_other", balance: -50,
transactions: [ tx(when_ago: 2.days) ])
assert_empty SimplefinItem::ReplacementDetector.new(@item).call
end
end