mirror of
https://github.com/we-promise/sure
synced 2026-04-25 17:15:07 +02:00
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:
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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!
|
||||
|
||||
67
app/models/simplefin_account/activity_summary.rb
Normal file
67
app/models/simplefin_account/activity_summary.rb
Normal 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
|
||||
@@ -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",
|
||||
|
||||
135
app/models/simplefin_item/replacement_detector.rb
Normal file
135
app/models/simplefin_item/replacement_detector.rb
Normal 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
|
||||
@@ -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 %>
|
||||
|
||||
31
app/views/simplefin_items/_activity_badge.html.erb
Normal file
31
app/views/simplefin_items/_activity_badge.html.erb
Normal 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 %>
|
||||
68
app/views/simplefin_items/_replacement_prompt.html.erb
Normal file
68
app/views/simplefin_items/_replacement_prompt.html.erb
Normal 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>
|
||||
@@ -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 %>
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user