Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

SimpleFIN: add a credit card balance sign override (#3243)

Tim Katz013612056055
diff --git a/app/controllers/credit_cards_controller.rb b/app/controllers/credit_cards_controller.rb
index 982ce5483d..e7e5ed7635 100644
--- a/app/controllers/credit_cards_controller.rb
+++ b/app/controllers/credit_cards_controller.rb
@@ -14,7 +14,10 @@ class CreditCardsController < ApplicationController
super
# Only apply provider settings once the account update succeeded (redirect);
# a failed update renders :edit and must not persist the flag.
- update_enable_banking_settings if response.redirect?
+ if response.redirect?
+ update_enable_banking_settings
+ update_simplefin_settings
+ end
end
private
@@ -23,16 +26,36 @@ class CreditCardsController < ApplicationController
.dig(:account, :enable_banking)
return if eb_params.blank?
- provider_account = @account.provider_account_for("EnableBankingAccount")
- return unless provider_account.present?
-
- provider_account.update!(
- treat_balance_as_available_credit: ActiveModel::Type::Boolean.new.cast(eb_params[:treat_balance_as_available_credit])
- )
-
- # Re-sync so the balance is reinterpreted right away instead of on the next scheduled sync
- if provider_account.saved_change_to_treat_balance_as_available_credit?
+ update_provider_setting(
+ provider_type: "EnableBankingAccount",
+ attribute: :treat_balance_as_available_credit,
+ value: ActiveModel::Type::Boolean.new.cast(eb_params[:treat_balance_as_available_credit])
+ ) do |provider_account|
+ # Re-sync so the balance is reinterpreted right away instead of on the next scheduled sync
provider_account.enable_banking_item.sync_later
end
end
+
+ def update_simplefin_settings
+ simplefin_params = params.permit(account: { simplefin: [ :balance_sign_override ] })
+ .dig(:account, :simplefin)
+ return if simplefin_params.blank?
+
+ override = simplefin_params[:balance_sign_override]
+ override = nil unless override.in?(%w[credit debt])
+
+ update_provider_setting(
+ provider_type: "SimplefinAccount",
+ attribute: :balance_sign_override,
+ value: override
+ ) { |provider_account| provider_account.simplefin_item.sync_later }
+ end
+
+ def update_provider_setting(provider_type:, attribute:, value:)
+ provider_account = @account.provider_account_for(provider_type)
+ return unless provider_account.present?
+
+ provider_account.update!(attribute => value)
+ yield provider_account if provider_account.saved_change_to_attribute?(attribute)
+ end
end
diff --git a/app/models/simplefin_account.rb b/app/models/simplefin_account.rb
index 55cc80a91a..e6273f68ea 100644
--- a/app/models/simplefin_account.rb
+++ b/app/models/simplefin_account.rb
@@ -19,6 +19,7 @@ class SimplefinAccount < ApplicationRecord
validates :name, :account_type, :currency, presence: true
validates :account_id, uniqueness: { scope: :simplefin_item_id, allow_nil: true }
+ validates :balance_sign_override, inclusion: { in: %w[credit debt], allow_nil: true }
validate :has_balance
# Helper to get account using new system first, falling back to legacy
diff --git a/app/models/simplefin_account/processor.rb b/app/models/simplefin_account/processor.rb
index 98cba64973..4df28c90f8 100644
--- a/app/models/simplefin_account/processor.rb
+++ b/app/models/simplefin_account/processor.rb
@@ -103,66 +103,77 @@ class SimplefinAccount::Processor
data: { sfa_id: simplefin_account.id }
)) rescue nil
else
- # 1) Try transaction-history heuristic when enabled
- begin
- result = SimplefinAccount::Liabilities::OverpaymentAnalyzer
- .new(simplefin_account, observed_balance: observed)
- .call
-
- case result.classification
- when :credit
- balance = -observed.abs
- Rails.logger.info(
- "SimpleFIN overpayment heuristic: classified as credit for sfa=#{simplefin_account.id} " \
- "tx_count=#{result.metrics[:tx_count]}"
- )
- Rails.logger.debug(
- "SimpleFIN overpayment heuristic (credit) amounts: sfa=#{simplefin_account.id} " \
- "observed=#{observed.to_s('F')} metrics=#{result.metrics.slice(:charges_total, :payments_total, :tx_count).inspect}"
- )
- Sentry.add_breadcrumb(Sentry::Breadcrumb.new(
- category: "simplefin",
- message: "liability_sign=credit",
- data: { sfa_id: simplefin_account.id }
- )) rescue nil
- when :debt
- balance = observed.abs
- Rails.logger.info(
- "SimpleFIN overpayment heuristic: classified as debt for sfa=#{simplefin_account.id} " \
- "tx_count=#{result.metrics[:tx_count]}"
- )
- Rails.logger.debug(
- "SimpleFIN overpayment heuristic (debt) amounts: sfa=#{simplefin_account.id} " \
- "observed=#{observed.to_s('F')} metrics=#{result.metrics.slice(:charges_total, :payments_total, :tx_count).inspect}"
- )
- Sentry.add_breadcrumb(Sentry::Breadcrumb.new(
- category: "simplefin",
- message: "liability_sign=debt",
- data: { sfa_id: simplefin_account.id }
- )) rescue nil
- else
- # 2) Fall back to existing sign-only logic (log unknown for observability)
- begin
+ # A user override is authoritative because some SimpleFIN feeds use
+ # the same sign for both debt and genuine credit balances.
+ case simplefin_account.balance_sign_override
+ when "credit"
+ balance = -observed.abs
+ Rails.logger.info("SimpleFIN liability sign: classification=credit_override sfa=#{simplefin_account.id}")
+ when "debt"
+ balance = observed.abs
+ Rails.logger.info("SimpleFIN liability sign: classification=debt_override sfa=#{simplefin_account.id}")
+ else
+ # Try transaction-history heuristic when enabled
+ begin
+ result = SimplefinAccount::Liabilities::OverpaymentAnalyzer
+ .new(simplefin_account, observed_balance: observed)
+ .call
+
+ case result.classification
+ when :credit
+ balance = -observed.abs
Rails.logger.info(
- "SimpleFIN overpayment heuristic: unknown for sfa=#{simplefin_account.id} " \
- "reason=#{result.reason} tx_count=#{result.metrics[:tx_count]}; falling back"
+ "SimpleFIN overpayment heuristic: classified as credit for sfa=#{simplefin_account.id} " \
+ "tx_count=#{result.metrics[:tx_count]}"
)
Rails.logger.debug(
- "SimpleFIN overpayment heuristic (unknown) amounts: sfa=#{simplefin_account.id} " \
- "observed=#{observed.to_s('F')} " \
- "charges_total=#{result.metrics[:charges_total]} payments_total=#{result.metrics[:payments_total]}"
+ "SimpleFIN overpayment heuristic (credit) amounts: sfa=#{simplefin_account.id} " \
+ "observed=#{observed.to_s('F')} metrics=#{result.metrics.slice(:charges_total, :payments_total, :tx_count).inspect}"
)
- rescue
- # no-op
+ Sentry.add_breadcrumb(Sentry::Breadcrumb.new(
+ category: "simplefin",
+ message: "liability_sign=credit",
+ data: { sfa_id: simplefin_account.id }
+ )) rescue nil
+ when :debt
+ balance = observed.abs
+ Rails.logger.info(
+ "SimpleFIN overpayment heuristic: classified as debt for sfa=#{simplefin_account.id} " \
+ "tx_count=#{result.metrics[:tx_count]}"
+ )
+ Rails.logger.debug(
+ "SimpleFIN overpayment heuristic (debt) amounts: sfa=#{simplefin_account.id} " \
+ "observed=#{observed.to_s('F')} metrics=#{result.metrics.slice(:charges_total, :payments_total, :tx_count).inspect}"
+ )
+ Sentry.add_breadcrumb(Sentry::Breadcrumb.new(
+ category: "simplefin",
+ message: "liability_sign=debt",
+ data: { sfa_id: simplefin_account.id }
+ )) rescue nil
+ else
+ # Fall back to existing sign-only logic (log unknown for observability)
+ begin
+ Rails.logger.info(
+ "SimpleFIN overpayment heuristic: unknown for sfa=#{simplefin_account.id} " \
+ "reason=#{result.reason} tx_count=#{result.metrics[:tx_count]}; falling back"
+ )
+ Rails.logger.debug(
+ "SimpleFIN overpayment heuristic (unknown) amounts: sfa=#{simplefin_account.id} " \
+ "observed=#{observed.to_s('F')} " \
+ "charges_total=#{result.metrics[:charges_total]} payments_total=#{result.metrics[:payments_total]}"
+ )
+ rescue
+ # no-op
+ end
+ balance = normalize_liability_balance(observed, bal, avail)
end
+ rescue NameError
+ # Analyzer not loaded; keep legacy behavior
+ balance = normalize_liability_balance(observed, bal, avail)
+ rescue => e
+ Rails.logger.warn("SimpleFIN overpayment heuristic error for sfa=#{simplefin_account.id}: #{e.class} - #{e.message}")
balance = normalize_liability_balance(observed, bal, avail)
end
- rescue NameError
- # Analyzer not loaded; keep legacy behavior
- balance = normalize_liability_balance(observed, bal, avail)
- rescue => e
- Rails.logger.warn("SimpleFIN overpayment heuristic error for sfa=#{simplefin_account.id}: #{e.class} - #{e.message}")
- balance = normalize_liability_balance(observed, bal, avail)
end
end
end
diff --git a/app/models/simplefin_item/importer.rb b/app/models/simplefin_item/importer.rb
index c56d709dde..ef4489bd08 100644
--- a/app/models/simplefin_item/importer.rb
+++ b/app/models/simplefin_item/importer.rb
@@ -159,6 +159,10 @@ class SimplefinItem::Importer
normalized = observed
if acct.accountable_type == "Loan"
normalized = observed.abs
+ elsif is_liability && sfa.balance_sign_override == "credit"
+ normalized = -observed.abs
+ elsif is_liability && sfa.balance_sign_override == "debt"
+ normalized = observed.abs
elsif is_liability
# Try the overpayment analyzer first (feature-flagged)
begin
diff --git a/app/views/credit_cards/_form.html.erb b/app/views/credit_cards/_form.html.erb
index 7209e118b5..15b7f3b83b 100644
--- a/app/views/credit_cards/_form.html.erb
+++ b/app/views/credit_cards/_form.html.erb
@@ -47,5 +47,21 @@
<% end %>
</div>
<% end %>
+
+ <% simplefin_account = account.provider_account_for("SimplefinAccount") if account.persisted? %>
+ <% if simplefin_account %>
+ <div class="space-y-1">
+ <%= form.fields_for :simplefin, simplefin_account do |simplefin_form| %>
+ <%= simplefin_form.select :balance_sign_override,
+ options_for_select([
+ [t("credit_cards.form.simplefin_balance_sign_auto"), ""],
+ [t("credit_cards.form.simplefin_balance_sign_debt"), "debt"],
+ [t("credit_cards.form.simplefin_balance_sign_credit"), "credit"]
+ ], simplefin_account.balance_sign_override),
+ { label: t("credit_cards.form.simplefin_balance_sign_label") } %>
+ <% end %>
+ <p class="text-secondary text-xs"><%= t("credit_cards.form.simplefin_balance_sign_description") %></p>
+ </div>
+ <% end %>
</div>
<% end %>
diff --git a/config/locales/views/credit_cards/en.yml b/config/locales/views/credit_cards/en.yml
index 486b4ab34c..5d792f9b00 100644
--- a/config/locales/views/credit_cards/en.yml
+++ b/config/locales/views/credit_cards/en.yml
@@ -13,6 +13,13 @@ en:
expiration_date: Expiration date
minimum_payment: Minimum payment
minimum_payment_placeholder: '100'
+ simplefin_balance_sign_auto: Automatic
+ simplefin_balance_sign_credit: Credit (bank owes you)
+ simplefin_balance_sign_debt: Debt (you owe the bank)
+ simplefin_balance_sign_description: Use an override only when SimpleFIN reports
+ an ambiguous sign. Automatic continues using transaction history and the
+ provider balance.
+ simplefin_balance_sign_label: SimpleFIN balance meaning
treat_balance_as_available_credit_description: Enable if your bank reports
this card's balance as remaining available credit instead of the amount
owed. The debt is then derived from the credit limit reported by your
diff --git a/db/migrate/20260828174500_add_balance_sign_override_to_simplefin_accounts.rb b/db/migrate/20260828174500_add_balance_sign_override_to_simplefin_accounts.rb
new file mode 100644
index 0000000000..f28e183a35
--- /dev/null
+++ b/db/migrate/20260828174500_add_balance_sign_override_to_simplefin_accounts.rb
@@ -0,0 +1,8 @@
+class AddBalanceSignOverrideToSimplefinAccounts < ActiveRecord::Migration[7.2]
+ def change
+ add_column :simplefin_accounts, :balance_sign_override, :string
+ add_check_constraint :simplefin_accounts,
+ "balance_sign_override IN ('credit', 'debt')",
+ name: "chk_simplefin_accounts_balance_sign_override"
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 2e4ada7d3e..cdc2abc4a2 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -2115,6 +2115,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_10_130000) do
t.string "account_type"
t.decimal "available_balance", precision: 19, scale: 4
t.datetime "balance_date"
+ t.string "balance_sign_override"
t.datetime "created_at", null: false
t.string "currency"
t.decimal "current_balance", precision: 19, scale: 4
@@ -2129,6 +2130,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_10_130000) do
t.index ["account_id"], name: "index_simplefin_accounts_on_account_id"
t.index ["simplefin_item_id", "account_id"], name: "idx_unique_sfa_per_item_and_upstream", unique: true, where: "(account_id IS NOT NULL)"
t.index ["simplefin_item_id"], name: "index_simplefin_accounts_on_simplefin_item_id"
+ t.check_constraint "balance_sign_override::text = ANY (ARRAY['credit'::character varying, 'debt'::character varying]::text[])", name: "chk_simplefin_accounts_balance_sign_override"
end
create_table "simplefin_items", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
diff --git a/test/controllers/credit_cards_controller_test.rb b/test/controllers/credit_cards_controller_test.rb
index 7fd20f99ae..e2f692182d 100644
--- a/test/controllers/credit_cards_controller_test.rb
+++ b/test/controllers/credit_cards_controller_test.rb
@@ -171,6 +171,75 @@ class CreditCardsControllerTest < ActionDispatch::IntegrationTest
assert_equal "Still works", @account.reload.name
end
+ test "updates SimpleFIN balance sign override when linked" do
+ simplefin_account = create_linked_simplefin_account
+
+ get edit_credit_card_path(@account)
+ assert_response :success
+ assert_match "balance_sign_override", response.body
+ assert_match I18n.t("credit_cards.form.simplefin_balance_sign_label"), response.body
+
+ assert_enqueued_with(job: SyncJob) do
+ patch credit_card_path(@account), params: {
+ account: {
+ name: @account.name,
+ accountable_type: "CreditCard",
+ simplefin: { balance_sign_override: "credit" }
+ }
+ }
+ end
+
+ assert_redirected_to @account
+ assert_equal "credit", simplefin_account.reload.balance_sign_override
+ end
+
+ test "clears SimpleFIN balance sign override when automatic is selected" do
+ simplefin_account = create_linked_simplefin_account
+ simplefin_account.update!(balance_sign_override: "credit")
+
+ patch credit_card_path(@account), params: {
+ account: {
+ name: @account.name,
+ accountable_type: "CreditCard",
+ simplefin: { balance_sign_override: "" }
+ }
+ }
+
+ assert_redirected_to @account
+ assert_nil simplefin_account.reload.balance_sign_override
+ end
+
+ test "does not persist SimpleFIN override when the account update fails" do
+ simplefin_account = create_linked_simplefin_account
+
+ patch credit_card_path(@account), params: {
+ account: {
+ name: "",
+ accountable_type: "CreditCard",
+ simplefin: { balance_sign_override: "credit" }
+ }
+ }
+
+ assert_response :unprocessable_entity
+ assert_nil simplefin_account.reload.balance_sign_override
+ end
+
+ test "normalizes an unsupported SimpleFIN balance sign to automatic" do
+ simplefin_account = create_linked_simplefin_account
+ simplefin_account.update!(balance_sign_override: "credit")
+
+ patch credit_card_path(@account), params: {
+ account: {
+ name: @account.name,
+ accountable_type: "CreditCard",
+ simplefin: { balance_sign_override: "unsupported" }
+ }
+ }
+
+ assert_redirected_to @account
+ assert_nil simplefin_account.reload.balance_sign_override
+ end
+
private
def create_linked_enable_banking_account
enable_banking_item = EnableBankingItem.create!(
@@ -191,4 +260,22 @@ class CreditCardsControllerTest < ActionDispatch::IntegrationTest
AccountProvider.create!(account: @account, provider: enable_banking_account)
enable_banking_account
end
+
+ def create_linked_simplefin_account
+ simplefin_item = SimplefinItem.create!(
+ family: @account.family,
+ name: "Test SimpleFIN",
+ access_url: "https://example.com/token"
+ )
+ simplefin_account = SimplefinAccount.create!(
+ simplefin_item: simplefin_item,
+ name: "Linked card",
+ account_id: "simplefin-linked-card",
+ currency: "USD",
+ account_type: "credit",
+ current_balance: -25
+ )
+ AccountProvider.create!(account: @account, provider: simplefin_account)
+ simplefin_account
+ end
end
diff --git a/test/models/simplefin_account_processor_test.rb b/test/models/simplefin_account_processor_test.rb
index b5361b3659..a537584854 100644
--- a/test/models/simplefin_account_processor_test.rb
+++ b/test/models/simplefin_account_processor_test.rb
@@ -28,6 +28,46 @@ class SimplefinAccountProcessorTest < ActiveSupport::TestCase
assert_equal BigDecimal("123.45"), acct.reload.balance
end
+ test "credit override preserves an ambiguous provider balance as a credit" do
+ sfin_acct = SimplefinAccount.create!(
+ simplefin_item: @item,
+ name: "Credit balance",
+ account_id: "cc_credit_override",
+ currency: "USD",
+ account_type: "credit",
+ current_balance: BigDecimal("-25"),
+ available_balance: BigDecimal("0"),
+ balance_sign_override: "credit"
+ )
+
+ acct = accounts(:credit_card)
+ acct.update!(simplefin_account: sfin_acct)
+
+ SimplefinAccount::Processor.new(sfin_acct).send(:process_account!)
+
+ assert_equal BigDecimal("-25"), acct.reload.balance
+ end
+
+ test "debt override preserves an ambiguous provider balance as debt" do
+ sfin_acct = SimplefinAccount.create!(
+ simplefin_item: @item,
+ name: "Debt balance",
+ account_id: "cc_debt_override",
+ currency: "USD",
+ account_type: "credit",
+ current_balance: BigDecimal("-25"),
+ available_balance: BigDecimal("0"),
+ balance_sign_override: "debt"
+ )
+
+ acct = accounts(:credit_card)
+ acct.update!(simplefin_account: sfin_acct)
+
+ SimplefinAccount::Processor.new(sfin_acct).send(:process_account!)
+
+ assert_equal BigDecimal("25"), acct.reload.balance
+ end
+
test "does not invert balance for asset accounts (depository)" do
sfin_acct = SimplefinAccount.create!(
simplefin_item: @item,
diff --git a/test/models/simplefin_account_test.rb b/test/models/simplefin_account_test.rb
index 1b4bceaea9..e33b42fc17 100644
--- a/test/models/simplefin_account_test.rb
+++ b/test/models/simplefin_account_test.rb
@@ -44,6 +44,25 @@ class SimplefinAccountTest < ActiveSupport::TestCase
assert_includes account.errors[:base], I18n.t("activerecord.errors.models.simplefin_account.no_balance")
end
+ test "accepts only supported balance sign overrides" do
+ @simplefin_account.balance_sign_override = "credit"
+ assert @simplefin_account.valid?
+
+ @simplefin_account.balance_sign_override = "debt"
+ assert @simplefin_account.valid?
+
+ @simplefin_account.balance_sign_override = "unsupported"
+ refute @simplefin_account.valid?
+ end
+
+ test "database rejects an unsupported balance sign override" do
+ @simplefin_account.balance_sign_override = "unsupported"
+
+ assert_raises ActiveRecord::StatementInvalid do
+ @simplefin_account.save!(validate: false)
+ end
+ end
+
test "can upsert snapshot data" do
balance_date = "2024-01-15T10:30:00Z"
snapshot = {
diff --git a/test/models/simplefin_item/importer_test.rb b/test/models/simplefin_item/importer_test.rb
index d8d4071c9f..c38c2f1b6a 100644
--- a/test/models/simplefin_item/importer_test.rb
+++ b/test/models/simplefin_item/importer_test.rb
@@ -35,6 +35,40 @@ class SimplefinItem::ImporterTest < ActiveSupport::TestCase
assert_equal 1911.72, credit_card.cash_balance
end
+ test "balances-only import honors a credit balance sign override" do
+ credit_card = accounts(:credit_card)
+ simplefin_account = create_simplefin_account("sf_credit_override_1", "Store Card", "credit", -48.48)
+ simplefin_account.update!(balance_sign_override: "credit")
+ credit_card.update!(simplefin_account_id: simplefin_account.id)
+
+ @importer.send(:import_account_minimal_and_balance, {
+ id: simplefin_account.account_id,
+ name: "Store Card",
+ balance: -48.48,
+ currency: "USD"
+ })
+
+ assert_equal(-48.48, credit_card.reload.balance)
+ assert_equal(-48.48, credit_card.cash_balance)
+ end
+
+ test "balances-only import honors a debt balance sign override" do
+ credit_card = accounts(:credit_card)
+ simplefin_account = create_simplefin_account("sf_debt_override_1", "Store Card", "credit", 48.48)
+ simplefin_account.update!(balance_sign_override: "debt")
+ credit_card.update!(simplefin_account_id: simplefin_account.id)
+
+ @importer.send(:import_account_minimal_and_balance, {
+ id: simplefin_account.account_id,
+ name: "Store Card",
+ balance: 48.48,
+ currency: "USD"
+ })
+
+ assert_equal 48.48, credit_card.reload.balance
+ assert_equal 48.48, credit_card.cash_balance
+ end
+
test "balances-only import keeps a positive loan principal positive" do
loan = accounts(:loan)
simplefin_account = create_simplefin_account("sf_loan_1", "Mortgage Loan", "loan", 250_000)