The personal finance app for everyone (by everyone)
Ruby
Keep Sophtron card charges as outflows on lender-signed feeds (#4886)
Rony HaCohena9aeefa73e14
diff --git a/app/jobs/sophtron_transactions_reprocess_job.rb b/app/jobs/sophtron_transactions_reprocess_job.rbnew file mode 100644index 0000000000..1d0b72de87--- /dev/null+++ b/app/jobs/sophtron_transactions_reprocess_job.rb@@ -0,0 +1,70 @@+# Re-signs a Sophtron account's stored transactions after its detected sign+# convention changes, then recalculates the linked account's balances.+#+# Runs outside the request that saved the override because it re-imports every+# stored transaction, and it does not wait for an item sync, which skips cards+# marked for manual sync. Re-signing is idempotent, so a retry starts over.+class SophtronTransactionsReprocessJob < ApplicationJob+ class IncompleteReprocess < StandardError; end+ class AccountSyncInProgress < StandardError; end++ queue_as :medium_priority++ SYNC_WAIT = 30.seconds++ # A transaction that failed to save keeps its old sign, and no other sync+ # retries it for a manual-sync card. Once retries run out, the transactions+ # that were re-signed still get a fresh calculation, behind the same guard.+ retry_on IncompleteReprocess, wait: :polynomially_longer, attempts: 5 do |job, error|+ job.record_failure(error, "Failed to re-sign Sophtron transactions after a sign convention change")+ job.class.perform_later(job.arguments.first, reprocess: false)+ end++ # A running sync may have read the amounts before they were re-signed, and+ # sync_later would join it rather than start a fresh calculation. sync_later+ # only joins a sync for Sync::VISIBLE_FOR after it was created, so these+ # retries outlast the guard, and running out of them means something else+ # is wrong; it is logged rather than joined.+ retry_on AccountSyncInProgress, wait: SYNC_WAIT, attempts: (Sync::VISIBLE_FOR / SYNC_WAIT).ceil + 2 do |job, error|+ job.record_failure(error, "Gave up waiting for a running sync after re-signing Sophtron transactions")+ end++ def perform(sophtron_account, reprocess: true)+ @sophtron_account = sophtron_account+ return unless account.present?++ if reprocess+ result = SophtronAccount::Transactions::Processor.new(sophtron_account).process+ unless result[:success]+ raise IncompleteReprocess, "#{result[:failed]} of #{result[:total]} Sophtron transactions could not be re-signed"+ end+ end++ raise AccountSyncInProgress if account.syncs.visible.where(status: "syncing").exists?++ account.sync_later+ end++ def account+ sophtron_account&.current_account+ end++ def record_failure(error, message)+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: message,+ source: self.class.name,+ provider_key: "sophtron",+ family: account&.family,+ account: account,+ account_provider: sophtron_account&.account_provider,+ metadata: { error_class: error.class.name, error_message: error.message }+ )+ end++ private+ def sophtron_account+ @sophtron_account ||= arguments.first+ end+enddiff --git a/app/models/sophtron_account.rb b/app/models/sophtron_account.rbindex 7264b2c76e..8bbf5a3826 100644--- a/app/models/sophtron_account.rb+++ b/app/models/sophtron_account.rb@@ -17,6 +17,7 @@# @attr [JSONB] raw_transactions_payload Raw transaction data from Sophtron API# @attr [DateTime] last_updated When Sophtron last updated this account# @attr [String, nil] balance_sign_override Credit card meaning: "credit", "debt", or nil for automatic+# @attr [Boolean, nil] lender_signed Feed sign convention detected when the override is savedclass SophtronAccount < ApplicationRecordinclude CurrencyNormalizable@@ -49,17 +50,45 @@ class SophtronAccount < ApplicationRecord# manual sync: SophtronItem::Syncer only processes automatic accounts, so the# override would sit unused until the user finishes that flow.#+ # The override is also the only signal for the feed's sign convention, so+ # the convention is detected here, from the balance the user is confirming,+ # and never inferred later from balances nobody looked at. Saving while the+ # balance is zero leaves it undetected until the override is saved again.+ # When the convention changes, the stored transactions are re-signed in the+ # background rather than in this request.+ ## @return [void]def apply_balance_sign_override!(override)transaction(requires_new: true) do- update!(balance_sign_override: override)- next unless saved_change_to_balance_sign_override? && current_account.present?-- SophtronAccount::Processor.new(self).process_account!- current_account.sync_later+ was_lender_signed = lender_signed?+ self.balance_sign_override = override+ detect_sign_convention if balance_sign_override_changed? || lender_signed.nil?+ save!+ next unless current_account.present?++ SophtronAccount::Processor.new(self).process_account! if saved_change_to_balance_sign_override?+ reprocess = lender_signed? != was_lender_signed+ SophtronTransactionsReprocessJob.perform_later(self) if reprocess+ current_account.sync_later if saved_change_to_balance_sign_override? || reprocessendend+ # The provider balance before Sure applies its sign convention.+ #+ # @return [Numeric]+ def observed_balance+ balance || available_balance || 0+ end++ # Whether this credit card's feed signs amounts from the lender's side, with+ # debt and charges positive. Automatic mode keeps the account-holder+ # convention.+ #+ # @return [Boolean]+ def lender_signed?+ lender_signed == true && current_account&.accountable_type == "CreditCard"+ end+def institution_nameinstitution_metadata.to_h["name"].presence || sophtron_item&.institution_nameend@@ -139,6 +168,18 @@ class SophtronAccount < ApplicationRecordprivate+ # Sophtron institutions differ in sign convention: a debt reported as+ # positive, or a credit reported as negative, comes from a lender-signed+ # feed. A zero balance carries no sign, so it leaves the convention unknown.+ def detect_sign_convention+ self.lender_signed =+ if balance_sign_override.blank? || observed_balance.zero?+ nil+ else+ (balance_sign_override == "debt") == observed_balance.positive?+ end+ end+def log_invalid_currency(currency_value)Rails.logger.warn("Invalid currency code '#{currency_value}' for Sophtron account #{id}, defaulting to USD")enddiff --git a/app/models/sophtron_account/processor.rb b/app/models/sophtron_account/processor.rbindex 922e5be4d2..991fa7bb55 100644--- a/app/models/sophtron_account/processor.rb+++ b/app/models/sophtron_account/processor.rb@@ -64,8 +64,7 @@ class SophtronAccount::Processorend# Update account balance from latest Sophtron data- observed = sophtron_account.balance || sophtron_account.available_balance || 0- balance = signed_balance(account, observed)+ balance = signed_balance(account, sophtron_account.observed_balance)# Normalize currency with fallback chain: parsed sophtron currency -> existing account currency -> USDcurrency = parse_currency(sophtron_account.currency) || account.currency || "USD"diff --git a/app/models/sophtron_entry/processor.rb b/app/models/sophtron_entry/processor.rbindex 6b57ac736e..ebaab6663a 100644--- a/app/models/sophtron_entry/processor.rb+++ b/app/models/sophtron_entry/processor.rb@@ -155,9 +155,11 @@ class SophtronEntry::Processor# Parses and converts the transaction amount.#- # Sophtron uses standard banking convention (negative = expense, positive = income)- # while Maybe uses inverted signs (positive = expense, negative = income).- # This method negates the amount to convert between conventions.+ # Sure stores outflows as positive and inflows as negative. Most Sophtron+ # feeds sign amounts from the account holder's side (negative = money out),+ # so the amount is negated. A credit card feed signed from the lender's side+ # already reports charges as positive and payments as negative, which is+ # Sure's convention, so its amounts are kept as reported.## @return [BigDecimal] The converted amount# @raise [ArgumentError] if the amount cannot be parsed@@ -171,10 +173,7 @@ class SophtronEntry::ProcessorBigDecimal("0")end- # Sophtron likely uses standard convention where negative is expense, positive is income- # Maybe expects opposite convention (expenses positive, income negative)- # So we negate the amount to convert from Sophtron to Maybe format- -parsed_amount+ sophtron_account.lender_signed? ? parsed_amount : -parsed_amountrescue ArgumentError => eRails.logger.error "Failed to parse Sophtron transaction amount: #{data[:amount].inspect} - #{e.message}"raisediff --git a/config/locales/views/credit_cards/en.yml b/config/locales/views/credit_cards/en.ymlindex 25f8532d89..06e6af1e05 100644--- a/config/locales/views/credit_cards/en.yml+++ b/config/locales/views/credit_cards/en.yml@@ -32,7 +32,9 @@ en:sophtron_balance_sign_credit: Credit (bank owes you)sophtron_balance_sign_debt: Debt (you owe the bank)sophtron_balance_sign_description: Use an override only when Sophtron reports- an ambiguous sign. Automatic continues negating credit card balances.+ an ambiguous sign. Automatic continues negating credit card balances and+ transactions. An override also corrects this card's transaction signs on the+ next sync.sophtron_balance_sign_label: Sophtron balance meaningsimplefin_balance_sign_auto: Automaticsimplefin_balance_sign_credit: Credit (bank owes you)diff --git a/db/migrate/20261111080000_add_lender_signed_to_sophtron_accounts.rb b/db/migrate/20261111080000_add_lender_signed_to_sophtron_accounts.rbnew file mode 100644index 0000000000..164ed016bd--- /dev/null+++ b/db/migrate/20261111080000_add_lender_signed_to_sophtron_accounts.rb@@ -0,0 +1,5 @@+class AddLenderSignedToSophtronAccounts < ActiveRecord::Migration[8.1]+ def change+ add_column :sophtron_accounts, :lender_signed, :boolean+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 78e444bdae..98021a1606 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[8.1].define(version: 2026_11_01_120000) do+ActiveRecord::Schema[8.1].define(version: 2026_11_11_080000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pg_catalog.plpgsql"enable_extension "pgcrypto"@@ -2590,6 +2590,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_01_120000) dot.string "customer_id"t.jsonb "institution_metadata"t.datetime "last_updated"+ t.boolean "lender_signed"t.boolean "manual_sync", default: false, null: falset.string "member_id"t.string "name", null: falsediff --git a/test/jobs/sophtron_transactions_reprocess_job_test.rb b/test/jobs/sophtron_transactions_reprocess_job_test.rbnew file mode 100644index 0000000000..d1f1c311f8--- /dev/null+++ b/test/jobs/sophtron_transactions_reprocess_job_test.rb@@ -0,0 +1,109 @@+require "test_helper"++class SophtronTransactionsReprocessJobTest < ActiveJob::TestCase+ setup do+ item = families(:dylan_family).sophtron_items.create!(+ name: "Sophtron",+ user_id: "developer-user",+ access_key: Base64.strict_encode64("secret-key")+ )+ @sophtron_account = item.sophtron_accounts.create!(+ account_id: "card-reprocess",+ name: "Card",+ currency: "USD",+ balance: 25,+ raw_transactions_payload: [+ { id: "charge", amount: "40", currency: "USD", date: "2026-05-01", merchant: "Coffee Shop" }+ ]+ )+ @account = accounts(:credit_card)+ AccountProvider.create!(account: @account, provider: @sophtron_account)+ end++ test "re-signs transactions imported before the convention was detected and syncs the account" do+ SophtronAccount::Transactions::Processor.new(@sophtron_account).process+ entry = @account.entries.find_by!(external_id: "sophtron_charge")+ assert_equal BigDecimal("-40"), entry.amount++ @sophtron_account.update!(balance_sign_override: "debt", lender_signed: true)+ Account.any_instance.expects(:sync_later).once++ SophtronTransactionsReprocessJob.perform_now(@sophtron_account)++ assert_equal BigDecimal("40"), entry.reload.amount+ end++ test "retries when a transaction could not be re-signed" do+ SophtronAccount::Transactions::Processor.any_instance.stubs(:process)+ .returns({ success: false, total: 1, imported: 0, failed: 1, errors: [] })+ Account.any_instance.expects(:sync_later).never++ assert_enqueued_with(job: SophtronTransactionsReprocessJob, args: [ @sophtron_account ]) do+ SophtronTransactionsReprocessJob.perform_now(@sophtron_account)+ end+ end++ test "records the failure and still syncs once retries run out" do+ SophtronAccount::Transactions::Processor.any_instance.stubs(:process)+ .returns({ success: false, total: 1, imported: 0, failed: 1, errors: [] })+ Account.any_instance.expects(:sync_later).once++ assert_difference -> { DebugLogEntry.where(provider_key: "sophtron", account: @account).count }, 1 do+ perform_enqueued_jobs(only: SophtronTransactionsReprocessJob) do+ SophtronTransactionsReprocessJob.perform_later(@sophtron_account)+ end+ end+ end++ test "after retries run out, the follow-up sync still waits for a running sync" do+ SophtronAccount::Transactions::Processor.any_instance.stubs(:process)+ .returns({ success: false, total: 1, imported: 0, failed: 1, errors: [] })+ running = @account.syncs.create!(status: "syncing")+ Account.any_instance.expects(:sync_later).never++ perform_enqueued_jobs(only: SophtronTransactionsReprocessJob) do+ SophtronTransactionsReprocessJob.perform_later(@sophtron_account)+ end++ assert_equal [ running ], @account.syncs.reload.to_a+ assert_equal 2, DebugLogEntry.where(provider_key: "sophtron", account: @account).count+ end++ test "a sync-only run does not re-sign transactions" do+ SophtronAccount::Transactions::Processor.expects(:new).never+ Account.any_instance.expects(:sync_later).once++ SophtronTransactionsReprocessJob.perform_now(@sophtron_account, reprocess: false)+ end++ test "waiting for a running sync outlasts the window in which sync_later would join it" do+ attempts = (Sync::VISIBLE_FOR / SophtronTransactionsReprocessJob::SYNC_WAIT).ceil + 2++ assert_operator (attempts - 1) * SophtronTransactionsReprocessJob::SYNC_WAIT, :>, Sync::VISIBLE_FOR+ end++ test "waits for a running account sync instead of joining it" do+ running = @account.syncs.create!(status: "syncing")++ assert_enqueued_with(job: SophtronTransactionsReprocessJob, args: [ @sophtron_account ]) do+ SophtronTransactionsReprocessJob.perform_now(@sophtron_account)+ end+ assert_equal [ running ], @account.syncs.reload.to_a+ end++ test "joins a pending account sync that has not read the amounts yet" do+ pending_sync = @account.syncs.create!++ assert_no_enqueued_jobs(only: SophtronTransactionsReprocessJob) do+ SophtronTransactionsReprocessJob.perform_now(@sophtron_account)+ end+ assert_equal [ pending_sync ], @account.syncs.reload.to_a+ end++ test "does nothing once the account is unlinked" do+ @sophtron_account.account_provider.destroy!+ SophtronAccount::Transactions::Processor.expects(:new).never++ SophtronTransactionsReprocessJob.perform_now(@sophtron_account.reload)+ end+enddiff --git a/test/models/sophtron_account_test.rb b/test/models/sophtron_account_test.rbindex 3275514c4f..53af368bb5 100644--- a/test/models/sophtron_account_test.rb+++ b/test/models/sophtron_account_test.rb@@ -1,6 +1,8 @@require "test_helper"class SophtronAccountTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper+test "upsert_sophtron_snapshot stores owning item institution metadata fallback" doitem = families(:dylan_family).sophtron_items.create!(name: "Sophtron Connection",@@ -50,6 +52,135 @@ class SophtronAccountTest < ActiveSupport::TestCaseassert_equal original_anchor, account.current_anchor_balanceend+ test "detects the feed convention from the override and the confirmed balance sign" do+ {+ [ nil, 25 ] => nil,+ [ "debt", 25 ] => true,+ [ "debt", -25 ] => false,+ [ "credit", -25 ] => true,+ [ "credit", 25 ] => false,+ [ "debt", 0 ] => nil+ }.each do |(override, balance), expected|+ sophtron_account = build_sophtron_account+ sophtron_account.update!(balance: balance)+ sophtron_account.apply_balance_sign_override!(override)++ if expected.nil?+ assert_nil sophtron_account.reload.lender_signed, "override=#{override.inspect} balance=#{balance}"+ else+ assert_equal expected, sophtron_account.reload.lender_signed, "override=#{override.inspect} balance=#{balance}"+ end+ sophtron_account.destroy!+ end+ end++ test "later balances do not change the detected convention" do+ sophtron_account = build_sophtron_account+ sophtron_account.apply_balance_sign_override!("debt")+ assert sophtron_account.lender_signed++ [ 0, -10, 30 ].each do |balance|+ sophtron_account.update!(balance: balance)+ assert sophtron_account.reload.lender_signed, "balance=#{balance}"+ end+ end++ test "a balance that arrives after an override saved at zero is not trusted until the override is saved again" do+ sophtron_account = build_sophtron_account+ sophtron_account.update!(balance: 0)+ sophtron_account.apply_balance_sign_override!("debt")+ assert_nil sophtron_account.lender_signed++ sophtron_account.update!(balance: -10)+ assert_nil sophtron_account.reload.lender_signed++ sophtron_account.update!(balance: 25)+ sophtron_account.apply_balance_sign_override!("debt")+ assert sophtron_account.reload.lender_signed+ end++ test "changing the override re-detects the convention and automatic clears it" do+ sophtron_account = build_sophtron_account+ sophtron_account.apply_balance_sign_override!("debt")+ assert sophtron_account.lender_signed++ sophtron_account.apply_balance_sign_override!("credit")+ assert_equal false, sophtron_account.lender_signed++ sophtron_account.apply_balance_sign_override!(nil)+ assert_nil sophtron_account.lender_signed+ end++ test "lender_signed? is true only for a lender-signed credit card" do+ Account.any_instance.stubs(:sync_later)+ sophtron_account = build_sophtron_account+ AccountProvider.create!(account: accounts(:credit_card), provider: sophtron_account)+ assert_not sophtron_account.lender_signed?++ sophtron_account.apply_balance_sign_override!("debt")+ assert sophtron_account.lender_signed?+ end++ test "lender_signed? is false for accounts that are not credit cards" do+ sophtron_account = build_sophtron_account+ sophtron_account.apply_balance_sign_override!("debt")+ AccountProvider.create!(account: accounts(:loan), provider: sophtron_account)++ assert_not sophtron_account.lender_signed?+ end++ test "a convention change queues re-signing of the stored transactions" do+ Account.any_instance.stubs(:sync_later)+ sophtron_account = build_sophtron_account+ AccountProvider.create!(account: accounts(:credit_card), provider: sophtron_account)++ assert_enqueued_with(job: SophtronTransactionsReprocessJob, args: [ sophtron_account ]) do+ sophtron_account.apply_balance_sign_override!("debt")+ end+ end++ test "re-saving an unchanged override that detects the convention queues re-signing" do+ sophtron_account = build_sophtron_account+ account = accounts(:credit_card)+ AccountProvider.create!(account: account, provider: sophtron_account)+ sophtron_account.update!(balance: 0)+ Account.any_instance.stubs(:sync_later)+ sophtron_account.apply_balance_sign_override!("debt")+ sophtron_account.update!(balance: 25)++ Account.any_instance.unstub(:sync_later)+ Account.any_instance.expects(:sync_later).once+ assert_enqueued_with(job: SophtronTransactionsReprocessJob) do+ sophtron_account.apply_balance_sign_override!("debt")+ end+ assert sophtron_account.reload.lender_signed+ end++ test "an override that keeps the account-holder convention does not queue re-signing" do+ Account.any_instance.stubs(:sync_later)+ sophtron_account = build_sophtron_account+ AccountProvider.create!(account: accounts(:credit_card), provider: sophtron_account)++ assert_no_enqueued_jobs(only: SophtronTransactionsReprocessJob) do+ sophtron_account.apply_balance_sign_override!("credit")+ end+ assert_equal false, sophtron_account.lender_signed+ end++ test "re-saving an unchanged override with nothing new to detect does nothing" do+ sophtron_account = build_sophtron_account+ AccountProvider.create!(account: accounts(:credit_card), provider: sophtron_account)+ Account.any_instance.stubs(:sync_later)+ sophtron_account.apply_balance_sign_override!("debt")++ Account.any_instance.unstub(:sync_later)+ Account.any_instance.expects(:sync_later).never+ SophtronAccount::Processor.any_instance.expects(:process_account!).never+ assert_no_enqueued_jobs(only: SophtronTransactionsReprocessJob) do+ sophtron_account.apply_balance_sign_override!("debt")+ end+ end+privatedef build_sophtron_accountitem = families(:dylan_family).sophtron_items.create!(diff --git a/test/models/sophtron_entry/processor_test.rb b/test/models/sophtron_entry/processor_test.rbnew file mode 100644index 0000000000..13b3044548--- /dev/null+++ b/test/models/sophtron_entry/processor_test.rb@@ -0,0 +1,79 @@+require "test_helper"++class SophtronEntry::ProcessorTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @item = @family.sophtron_items.create!(+ name: "Sophtron",+ user_id: "developer-user",+ access_key: Base64.strict_encode64("secret-key")+ )+ end++ test "negates amounts from an account-holder-signed depository feed" do+ sophtron_account = create_sophtron_account(account_id: "dep_1", balance: 1000)+ account = link_account(accounts(:depository), sophtron_account)++ assert_equal BigDecimal("12.34"), process(sophtron_account, id: "t1", amount: "-12.34").amount+ assert_equal BigDecimal("-500"), process(sophtron_account, id: "t2", amount: "500").amount+ assert_equal 2, account.entries.where(source: "sophtron").count+ end++ test "automatic credit card mode keeps negating amounts" do+ sophtron_account = create_sophtron_account(account_id: "cc_auto", balance: 250)+ link_account(accounts(:credit_card), sophtron_account)++ assert_equal BigDecimal("-40"), process(sophtron_account, id: "t1", amount: "40").amount+ end++ test "credit card with a debt reported as positive keeps charges as outflows" do+ sophtron_account = create_sophtron_account(account_id: "cc_lender", balance: 250, balance_sign_override: "debt")+ link_account(accounts(:credit_card), sophtron_account)++ assert_equal BigDecimal("40"), process(sophtron_account, id: "charge", amount: "40").amount+ assert_equal BigDecimal("-100"), process(sophtron_account, id: "payment", amount: "-100").amount+ end++ test "credit card with a debt reported as negative still negates amounts" do+ sophtron_account = create_sophtron_account(account_id: "cc_holder", balance: -250, balance_sign_override: "debt")+ link_account(accounts(:credit_card), sophtron_account)++ assert_equal BigDecimal("40"), process(sophtron_account, id: "charge", amount: "-40").amount+ assert_equal BigDecimal("-100"), process(sophtron_account, id: "payment", amount: "100").amount+ end++ test "paying a lender-signed card down to zero keeps charges as outflows on reprocessing" do+ sophtron_account = create_sophtron_account(account_id: "cc_paid_off", balance: 25, balance_sign_override: "debt")+ link_account(accounts(:credit_card), sophtron_account)+ assert_equal BigDecimal("40"), process(sophtron_account, id: "charge", amount: "40").amount++ sophtron_account.update!(balance: 0)++ assert_equal BigDecimal("40"), process(sophtron_account, id: "charge", amount: "40").amount+ end++ private+ def process(sophtron_account, id:, amount:)+ SophtronEntry::Processor.new(+ { id: id, accountId: sophtron_account.account_id, amount: amount, currency: "USD", date: "2026-05-01", merchant: "Coffee Shop" },+ sophtron_account: sophtron_account+ ).process+ end++ def create_sophtron_account(account_id:, balance:, balance_sign_override: nil)+ sophtron_account = @item.sophtron_accounts.create!(+ account_id: account_id,+ name: account_id,+ currency: "USD",+ balance: balance+ )+ sophtron_account.apply_balance_sign_override!(balance_sign_override) if balance_sign_override+ sophtron_account+ end++ def link_account(account, sophtron_account)+ AccountProvider.create!(account: account, provider: sophtron_account)+ sophtron_account.reload+ account+ end+end