The personal finance app for everyone (by everyone)
Ruby
Fill a blank credit card APR from Redbark account details (#5452)
jaysbeekayd4ac49f9a008
diff --git a/app/models/redbark_account/credit_card_details_processor.rb b/app/models/redbark_account/credit_card_details_processor.rbnew file mode 100644index 0000000000..761bfedbf4--- /dev/null+++ b/app/models/redbark_account/credit_card_details_processor.rb@@ -0,0 +1,184 @@+# frozen_string_literal: true++# Fills a credit card's blank APR from the product details the bank publishes+# through `GET /v1/account-details`.+#+# FILL-BLANK ONLY, unlike Plaid, which writes the APR on every sync. Plaid's+# figure is the issuer's for this account; Redbark's `lendingRates` describe the+# PRODUCT. A value already on the card -- typed, imported or restored -- is at+# least as good evidence as a product sheet, so this only fills a gap.+#+# The annual fee is deliberately not read: `fees` publishes the product's+# ceiling ("the Annual Fee that may apply is up to ..."), not what this+# account is charged.+#+# `lendingRate` is not read: its meaning for a card is undocumented. The+# PURCHASE entries in `lendingRates` are the rate that applies to spending.+# A 0% purchase rate is taken as promotional and not recorded.+#+# A card's details are fetched at most once per REFRESH_WINDOW, and any+# payload stored within it is used, so a day that fails to process is retried+# on the next sync. Warnings are logged once per window (see .warn_once).+class RedbarkAccount::CreditCardDetailsProcessor+ SOURCE = "redbark"+ REFRESH_WINDOW = 7.days++ attr_reader :redbark_account, :as_of++ # Shared with RedbarkItem::Importer, which fetches details only for these.+ def self.needs_apr?(card)+ card.apr.blank? && !card.locked?(:apr)+ end++ # Logs a warning unless the same source and message were already logged for+ # `key` (a redbark_account_id, or a redbark_item_id for a whole batch) in+ # the last REFRESH_WINDOW, so a lasting problem is reported once, not every+ # sync. `account_provider` ties a card's warning to its connection; it is+ # not part of the dedupe key.+ def self.warn_once(message, source:, family:, key:, account_provider: nil, **metadata)+ logged = DebugLogEntry.where(source: source, message: message)+ .where(created_at: REFRESH_WINDOW.ago..)+ .where("metadata @> ?", key.to_json)+ return if logged.exists?++ DebugLogEntry.capture(+ category: "provider_sync",+ level: "warn",+ message: message,+ source: source,+ provider_key: "redbark",+ family: family,+ account_provider: account_provider,+ metadata: metadata.merge(key)+ )+ end++ def initialize(redbark_account, as_of:)+ @redbark_account = redbark_account+ @as_of = as_of+ end++ # Never raises: an unexpected payload is logged so the rest of the sync+ # still runs.+ def process+ return unless card+ return unless self.class.needs_apr?(card)+ return if details.blank?+ return unless details_fetched_recently?++ rate = purchase_rate+ write(apr: rate) if rate+ rescue StandardError => e+ warn_once("Redbark card details could not be processed (#{e.class.name})", message: e.message)+ end++ private+ # The APR is only ever filled where blank, so a payload from earlier in+ # the window is as good as one from today.+ def details_fetched_recently?+ fetched_at = redbark_account.account_details_fetched_at+ return false if fetched_at.blank?++ redbark_account.redbark_item.family.local_date(fetched_at) > as_of.to_date - REFRESH_WINDOW+ end++ def card+ return @card if defined?(@card)++ account = redbark_account.current_account+ @card = account&.accountable_type == "CreditCard" ? account.accountable : nil+ end++ def details+ @details ||= redbark_account.raw_account_details_payload&.deep_symbolize_keys || {}+ end++ # A bank may list the purchase rate more than once, so agreement is judged+ # on distinct values. A tiered entry is several rates in one, keyed to a+ # balance the payload does not give, so it is left out rather than allowed+ # to disagree. A blank or unparseable entry is skipped, not a veto.+ def purchase_rate+ entries = Array(details[:lendingRates]).select do |entry|+ entry.is_a?(Hash) &&+ entry[:rateType].to_s.casecmp("PURCHASE").zero? &&+ Array(entry[:tiers]).empty?+ end++ values = entries.filter_map { |entry| parse_decimal(entry[:rate]) }+ return nil if values.empty?++ distinct = values.uniq+ if distinct.size > 1+ warn_once("Redbark reported several purchase rates for a card; recording none", rates: distinct.map(&:to_s).sort)+ return nil+ end++ to_percentage(distinct.first)+ end++ # The API reports fractions: "0.1999" is 19.99%. `credit_cards.apr` is a+ # percentage with two decimal places.+ def to_percentage(decimal)+ rate = (decimal * 100).round(2)+ if rate.zero?+ warn_once("Redbark reported a 0% purchase rate for a card; taking it as promotional")+ return nil+ end+ return rate if rate.between?(0, 100)++ warn_once("Redbark reported a card rate outside 0..100%; ignoring it", value: decimal.to_s)+ nil+ end++ def parse_decimal(value)+ return nil if value.blank?++ decimal = BigDecimal(value.to_s)+ raise ArgumentError, "not finite" unless decimal.finite?++ decimal+ rescue ArgumentError, TypeError+ warn_once("Redbark reported an unparseable card rate", value: value.to_s)+ nil+ end++ # Through Enrichable, as the loan processor writes: locked attributes are+ # skipped and provenance is recorded. A refusal is rolled back and logged+ # rather than raised, so it cannot fail the sync.+ def write(attrs)+ ActiveRecord::Base.transaction do+ card.enrich_attributes(attrs, source: SOURCE)+ raise ActiveRecord::Rollback if card.errors.any?+ end+ return if card.errors.empty?++ capture(+ "Redbark card detail refused by the model",+ credit_card_id: card.id,+ attributes: attrs.keys.map(&:to_s),+ errors: card.errors.full_messages+ )+ card.restore_attributes(attrs.keys.map(&:to_s))+ card.errors.clear+ end++ def warn_once(message, **metadata)+ self.class.warn_once(+ message, source: self.class.name, family: redbark_account.redbark_item&.family,+ key: { redbark_account_id: redbark_account.id }, account_provider: redbark_account.account_provider, **metadata+ )+ end++ def capture(message, **metadata)+ DebugLogEntry.capture(+ category: "provider_sync",+ level: "warn",+ message: message,+ source: self.class.name,+ provider_key: "redbark",+ family: redbark_account.redbark_item&.family,+ account_provider: redbark_account.account_provider,+ metadata: metadata.merge(redbark_account_id: redbark_account.id)+ )+ end+enddiff --git a/app/models/redbark_account/processor.rb b/app/models/redbark_account/processor.rbindex 9b2865b6b2..dea0214e5f 100644--- a/app/models/redbark_account/processor.rb+++ b/app/models/redbark_account/processor.rb@@ -48,6 +48,8 @@ class RedbarkAccount::Processor# failure here cannot cost the user their entries; a raise would be caught# by RedbarkItem#process_accounts and logged per account.RedbarkAccount::LoanDetailsProcessor.new(redbark_account, as_of: as_of).process+ # A card's APR, filled only where blank.+ RedbarkAccount::CreditCardDetailsProcessor.new(redbark_account, as_of: as_of).process# Trigger immediate UI refresh so entries appear in the activity feedaccount.broadcast_sync_completediff --git a/app/models/redbark_item/importer.rb b/app/models/redbark_item/importer.rbindex 47ca88e0d8..b570d25cfb 100644--- a/app/models/redbark_item/importer.rb+++ b/app/models/redbark_item/importer.rb@@ -25,8 +25,8 @@ class RedbarkItem::Importer# Step 2: For linked accounts only, fetch transactions and balances.# Unlinked accounts just need basic info (name, institution) for the setup modal.- # `account_provider: :account` is preloaded because the loan filter in- # import_loan_account_details reads `current_account` for every linked+ # `account_provider: :account` is preloaded because the account-type filter+ # in import_account_details reads `current_account` for every linked# account, which is a query each without it.linked_accounts = redbark_item.linked_redbark_accounts.includes(account_provider: :account).to_a@@ -37,7 +37,7 @@ class RedbarkItem::Importerendimport_balances(linked_accounts)- import_loan_account_details(linked_accounts)+ import_account_details(linked_accounts)# Store import stats on the item as the raw snapshotredbark_item.upsert_redbark_snapshot!(stats)@@ -208,18 +208,25 @@ class RedbarkItem::Importerendend- # Loans only, and only when there are any: `account-details` is the one- # endpoint that reports a rate (we-promise/sure#3891), and for every other account type it- # would be a request per sync for something nothing reads.+ # Loans, and credit cards that still need an APR, and only when there are+ # any: `account-details` is the one endpoint that reports a rate, and for+ # every other account it would be a request per sync for something nothing+ # reads. Cards are a batch of their own (store_card_account_details).## A failure here leaves the payload untouched and the sync green, exactly as# a failed balances fetch does. The processor treats "never fetched" and# "fetch failed" alike, because for a rate they mean the same thing:# nothing was reported.- def import_loan_account_details(linked_accounts)- eligible_accounts = balance_eligible_accounts(linked_accounts).select do |redbark_account|- redbark_account.current_account&.accountable_type == "Loan"- end+ def import_account_details(linked_accounts)+ eligible_accounts = balance_eligible_accounts(linked_accounts)+ loans = eligible_accounts.select { |redbark_account| redbark_account.current_account&.accountable_type == "Loan" }+ cards = eligible_accounts.select { |redbark_account| card_details_due?(redbark_account) }++ store_loan_account_details(loans)+ store_card_account_details(cards)+ end++ def store_loan_account_details(eligible_accounts)account_ids = eligible_accounts.map(&:redbark_account_id).compactreturn if account_ids.empty?@@ -249,10 +256,54 @@ class RedbarkItem::Importerendend+ def card_details_due?(redbark_account)+ account = redbark_account.current_account+ return false unless account&.accountable_type == "CreditCard"+ return false unless RedbarkAccount::CreditCardDetailsProcessor.needs_apr?(account.accountable)++ last_attempt_at = redbark_account.account_details_fetched_at+ last_attempt_at.blank? || last_attempt_at <= fetched_at - RedbarkAccount::CreditCardDetailsProcessor::REFRESH_WINDOW+ end++ # A card's product details rarely change, so each card is tried at most+ # once per window: its stamp records every attempt -- stored, left out by+ # the provider, or failed -- not only a stored payload. The payload is+ # replaced on every attempt, cleared when there is none, so a stamp never+ # vouches for details from an earlier attempt. A batch of its own,+ # so a card id the endpoint rejects cannot push the loans into per-account+ # retries; a failure is logged once per window, never a sync error.+ def store_card_account_details(cards)+ return if cards.empty?++ begin+ details_by_id = fetch_account_details_with_fallback(cards.map(&:redbark_account_id), log: method(:warn_card_failure))+ .index_by { |detail| detail[:accountId].to_s }++ cards.each do |redbark_account|+ detail = details_by_id[redbark_account.redbark_account_id]+ redbark_account.update!(raw_account_details_payload: detail.presence, account_details_fetched_at: fetched_at)+ stats["account_details_updated"] = stats.fetch("account_details_updated", 0) + 1 if detail.present?+ end+ rescue Provider::Redbark::AuthenticationError+ raise+ rescue => e+ warn_card_failure("Card account details fetch failed; clearing previous details", e)+ RedbarkAccount.where(id: cards.map(&:id)).update_all(raw_account_details_payload: nil, account_details_fetched_at: fetched_at)+ end+ end++ def warn_card_failure(message, error, account_id: nil)+ RedbarkAccount::CreditCardDetailsProcessor.warn_once(+ message, source: self.class.name, family: redbark_item.family,+ key: account_id ? { account_id: account_id } : { redbark_item_id: redbark_item.id },+ error_class: error.class.name, error: error.message+ )+ end+# The batch is rejected whole when one id is stale or of the wrong# category, exactly as the balances batch is, so one bad account must not# cost every other loan its rate. Mirrors fetch_balances_with_fallback.- def fetch_account_details_with_fallback(account_ids)+ def fetch_account_details_with_fallback(account_ids, log: method(:capture_failure))stats["api_requests"] = stats.fetch("api_requests", 0) + 1redbark_provider.get_account_details(account_ids: account_ids)rescue Provider::Redbark::AuthenticationError@@ -261,7 +312,7 @@ class RedbarkItem::Importerraise unless %i[not_found bad_request].include?(e.error_type)raise if account_ids.size <= 1- capture_failure("Batched account details call rejected; retrying per account", e)+ log.call("Batched account details call rejected; retrying per account", e)account_ids.flat_map do |account_id|begin@@ -270,7 +321,7 @@ class RedbarkItem::Importerrescue Provider::Redbark::AuthenticationErrorraiserescue Provider::Redbark::Error => account_error- capture_failure("Account details fetch failed for account; keeping previous details", account_error, account_id: account_id)+ log.call("Account details fetch failed for account", account_error, account_id: account_id)[]endenddiff --git a/test/models/redbark_account/credit_card_details_processor_test.rb b/test/models/redbark_account/credit_card_details_processor_test.rbnew file mode 100644index 0000000000..4c9b0fb5fd--- /dev/null+++ b/test/models/redbark_account/credit_card_details_processor_test.rb@@ -0,0 +1,353 @@+# frozen_string_literal: true++require "test_helper"++# A Redbark-linked card's APR, read from the product details the bank publishes+# through `/v1/account-details`. Rates there are FRACTIONS as strings: "0.1999"+# is 19.99%. A bank may list the purchase rate more than once, beside a cash+# advance rate.+class RedbarkAccount::CreditCardDetailsProcessorTest < ActiveSupport::TestCase+ setup do+ @redbark_account = redbark_accounts(:savings_account)+ @family = @redbark_account.redbark_item.family+ @as_of = Date.new(2026, 11, 20)++ @account = @family.accounts.create!(+ name: "Credit card", balance: 1_000, currency: "AUD", accountable: CreditCard.new+ )+ @card = @account.accountable++ @redbark_account.ensure_account_provider!(@account)+ @redbark_account.reload+ end++ # --- APR ---------------------------------------------------------------++ test "a blank APR is filled from the purchase rate the bank lists twice" do+ detail lendingRates: [+ purchase("0.1999"),+ purchase("0.1999", additionalInfo: "Standard balance transfer rate."),+ rate("CASH_ADVANCE", "0.2199")+ ]++ process++ assert_equal BigDecimal("19.99"), @card.reload.apr+ end++ test "two spellings of the same purchase rate are one rate" do+ detail lendingRates: [ purchase("0.1999"), purchase("0.19990") ]++ process++ assert_equal BigDecimal("19.99"), @card.reload.apr,+ "the same rate written with a trailing zero was read as a disagreement"+ end++ test "the rate is rounded to the column's two places, not truncated" do+ detail lendingRates: [ purchase("0.19999") ]++ process++ assert_equal BigDecimal("20.00"), @card.reload.apr+ end++ test "a tiered purchase entry is ignored, not outvoted" do+ detail lendingRates: [+ purchase("0.1999"),+ purchase("0.2499", tiers: [ { name: "Band 1", minimumValue: "0" } ])+ ]++ process++ assert_equal BigDecimal("19.99"), @card.reload.apr+ end++ test "a cash advance rate alone is not an APR" do+ detail lendingRates: [ rate("CASH_ADVANCE", "0.2199") ]++ process++ assert_nil @card.reload.apr+ end++ # lendingRate's meaning for a card is undocumented; only PURCHASE is read.+ test "a headline lendingRate with no purchase entry fills nothing" do+ detail lendingRate: "0.1499", lendingRates: []++ process++ assert_nil @card.reload.apr+ end++ test "purchase rates that disagree record nothing and say so" do+ detail lendingRates: [ purchase("0.1999"), purchase("0.0999") ]++ assert_difference -> { DebugLogEntry.where(source: RedbarkAccount::CreditCardDetailsProcessor.name).count }, 1 do+ process+ end++ assert_nil @card.reload.apr+ end++ test "a conflicting-rate warning names the card's connection" do+ detail lendingRates: [ purchase("0.1999"), purchase("0.0999") ]++ assert_difference -> { DebugLogEntry.where(account_provider: @redbark_account.account_provider, account: @account).count }, 1 do+ process+ end+ assert_equal [ "Redbark reported several purchase rates for a card; recording none" ], DebugLogEntry.where(account_provider: @redbark_account.account_provider).pluck(:message)+ end++ test "a refused write names the card's connection" do+ detail lendingRates: [ purchase("0.1999") ]+ @card.define_singleton_method(:valid?) do |*|+ errors.add(:apr, "is refused")+ false+ end+ RedbarkAccount.any_instance.stubs(:current_account).returns(@account)++ assert_difference -> { DebugLogEntry.where(account_provider: @redbark_account.account_provider, account: @account).count }, 1 do+ process+ end+ assert_equal [ "Redbark card detail refused by the model" ], DebugLogEntry.where(account_provider: @redbark_account.account_provider).pluck(:message)+ assert_nil @card.reload.apr+ end++ test "purchase rates that disagree are logged once across syncs" do+ detail lendingRates: [ purchase("0.1999"), purchase("0.0999") ]++ assert_difference -> { DebugLogEntry.where(source: RedbarkAccount::CreditCardDetailsProcessor.name).count }, 1 do+ process+ process+ end+ end++ test "a rate that rounds to 0% is not written and is logged" do+ detail lendingRates: [ purchase("0.00001") ]++ assert_difference -> { DebugLogEntry.where(source: RedbarkAccount::CreditCardDetailsProcessor.name).count }, 1 do+ process+ end++ assert_nil @card.reload.apr+ end++ test "the 0..100 check reads the rounded percentage" do+ detail lendingRates: [ purchase("1.000004") ]++ process++ assert_equal BigDecimal("100.00"), @card.reload.apr+ end++ test "a non-finite rate is logged as unparseable" do+ detail lendingRates: [ purchase("NaN") ]++ assert_difference -> { DebugLogEntry.where(source: RedbarkAccount::CreditCardDetailsProcessor.name, message: "Redbark reported an unparseable card rate").count }, 1 do+ process+ end++ assert_nil @card.reload.apr+ end++ test "a 0% purchase rate is not written and is logged" do+ detail lendingRates: [ purchase("0") ]++ assert_difference -> { DebugLogEntry.where(source: RedbarkAccount::CreditCardDetailsProcessor.name).count }, 1 do+ process+ end++ assert_nil @card.reload.apr+ end++ test "a blank purchase entry does not veto the valid ones" do+ detail lendingRates: [ purchase(""), purchase("0.1999") ]++ process++ assert_equal BigDecimal("19.99"), @card.reload.apr+ end++ test "an unparseable purchase entry is logged and the valid ones are used" do+ detail lendingRates: [ purchase("n/a"), purchase("0.1999") ]++ assert_difference -> { DebugLogEntry.where(source: RedbarkAccount::CreditCardDetailsProcessor.name).count }, 1 do+ process+ end++ assert_equal BigDecimal("19.99"), @card.reload.apr+ end++ test "a payload that is not an object is logged once, not raised" do+ @redbark_account.update!(raw_account_details_payload: [ "unexpected" ], account_details_fetched_at: @as_of.in_time_zone)++ assert_difference -> { DebugLogEntry.where(source: RedbarkAccount::CreditCardDetailsProcessor.name).count }, 1 do+ assert_nothing_raised { process }+ process+ end++ assert_nil @card.reload.apr+ end++ test "a processing failure of another kind is logged separately" do+ detail lendingRates: [ purchase("0.1999") ]+ RedbarkAccount::CreditCardDetailsProcessor.any_instance.stubs(:purchase_rate).raises(ArgumentError).then.raises(RuntimeError)++ assert_difference -> { DebugLogEntry.where(source: RedbarkAccount::CreditCardDetailsProcessor.name).count }, 2 do+ process+ process+ end+ end++ test "a card with an APR never reads its details" do+ @card.update!(apr: 12.5)+ @redbark_account.update!(raw_account_details_payload: [ "unexpected" ], account_details_fetched_at: @as_of.in_time_zone)++ assert_no_difference -> { DebugLogEntry.count } do+ process+ end+ end++ test "a card with a locked APR never reads its details" do+ @card.lock_attr!(:apr)+ @redbark_account.update!(raw_account_details_payload: [ "unexpected" ], account_details_fetched_at: @as_of.in_time_zone)++ assert_no_difference -> { DebugLogEntry.count } do+ process+ end+ end++ test "a rate outside 0..100 percent is ignored" do+ detail lendingRates: [ purchase("1.5") ]++ process++ assert_nil @card.reload.apr+ end++ test "an unparseable rate is ignored" do+ detail lendingRates: [ purchase("n/a") ]++ process++ assert_nil @card.reload.apr+ end++ # --- Annual fee --------------------------------------------------------++ # The published fee is the product's ceiling ("up to $190"), not what this+ # account is charged, so it is never copied onto the card.+ test "a published yearly fee does not fill a blank annual fee" do+ detail lendingRates: [ purchase("0.1999") ], fees: [ fee("PERIODIC", "190.00", "P1Y", name: "Annual Fee") ]++ process++ @card.reload+ assert_equal BigDecimal("19.99"), @card.apr+ assert_nil @card.annual_fee+ end++ # --- What is never written ---------------------------------------------++ test "an APR already on the card is kept" do+ @card.update!(apr: 12.5)+ detail lendingRates: [ purchase("0.1999") ]++ assert_no_difference -> { DataEnrichment.where(enrichable: @card).count } do+ process+ end++ assert_equal BigDecimal("12.5"), @card.reload.apr+ end++ test "a locked blank APR stays blank" do+ @card.lock_attr!(:apr)+ detail lendingRates: [ purchase("0.1999") ]++ process++ assert_nil @card.reload.apr, "a locked APR was written by the provider"+ end++ test "a snapshot older than the refresh window is not acted on" do+ detail lendingRates: [ purchase("0.1999") ], fetched_at: (@as_of - 7).in_time_zone++ process++ assert_nil @card.reload.apr+ end++ test "a snapshot from earlier in the refresh window is used" do+ detail lendingRates: [ purchase("0.1999") ], fetched_at: (@as_of - 6).in_time_zone++ process++ assert_equal BigDecimal("19.99"), @card.reload.apr+ end++ test "a warning is logged again once the refresh window has passed" do+ detail lendingRates: [ purchase("0.1999"), purchase("0.0999") ]+ process++ travel_to 8.days.from_now do+ assert_difference -> { DebugLogEntry.where(source: RedbarkAccount::CreditCardDetailsProcessor.name).count }, 1 do+ process+ end+ end+ end++ test "a card with no details is left alone" do+ process++ assert_nil @card.reload.apr+ end++ test "an account that is not a credit card is left alone" do+ loan_account = @family.accounts.create!(+ name: "Loan", balance: 1_000, currency: "AUD", accountable: Loan.new+ )+ @redbark_account.ensure_account_provider!(loan_account)+ detail lendingRates: [ purchase("0.1999") ]++ assert_no_difference -> { DataEnrichment.count } do+ process+ end+ assert_nil @card.reload.apr+ end++ test "the write is attributed to redbark" do+ detail lendingRates: [ purchase("0.1999") ]++ process++ assert_equal [ "redbark" ], DataEnrichment.where(enrichable: @card, attribute_name: "apr").pluck(:source)+ end++ private+ def detail(fetched_at: @as_of.in_time_zone, **payload)+ @redbark_account.update!(+ raw_account_details_payload: { "accountId" => @redbark_account.redbark_account_id }.merge(+ payload.deep_stringify_keys+ ),+ account_details_fetched_at: fetched_at+ )+ @redbark_account.reload+ end++ def process+ RedbarkAccount::CreditCardDetailsProcessor.new(@redbark_account, as_of: @as_of).process+ end++ def purchase(value, **extra)+ rate("PURCHASE", value, **extra)+ end++ def rate(type, value, **extra)+ { rateType: type, rate: value, calculationFrequency: "P1D", applicationFrequency: "P1M" }.merge(extra)+ end++ def fee(type, amount, additional_value, name: "Fee")+ { name: name, feeType: type, amount: amount, currency: "AUD", additionalValue: additional_value }+ end+enddiff --git a/test/models/redbark_account/processor_test.rb b/test/models/redbark_account/processor_test.rbindex bb5f24ebbc..0ac4e73b33 100644--- a/test/models/redbark_account/processor_test.rb+++ b/test/models/redbark_account/processor_test.rb@@ -138,6 +138,31 @@ class RedbarkAccount::ProcessorTest < ActiveSupport::TestCaseassert_equal BigDecimal("842.15"), card.reload.balanceend+ # A sync carries the card's published purchase rate onto+ # a blank APR, so the processor must run the card details step.+ test "processor fills a blank credit card APR from this sync's account details" do+ card, ra = link(CreditCard, provider: "fiskil", balance: "-842.15")+ as_of = Date.new(2026, 11, 20)+ ra.update!(+ raw_account_details_payload: { "lendingRates" => [ { "rateType" => "PURCHASE", "rate" => "0.1999" } ] },+ account_details_fetched_at: as_of.in_time_zone+ )++ RedbarkAccount::Processor.new(ra.reload, as_of: as_of).process++ assert_equal BigDecimal("19.99"), card.reload.accountable.apr+ end++ test "a card details failure does not skip the sync broadcast" do+ card, ra = link(CreditCard, provider: "fiskil", balance: "-842.15")+ as_of = Date.new(2026, 11, 20)+ ra.update!(raw_account_details_payload: [ "unexpected" ], account_details_fetched_at: as_of.in_time_zone)+ Account.any_instance.expects(:broadcast_sync_complete).once++ assert_nothing_raised { RedbarkAccount::Processor.new(ra.reload, as_of: as_of).process }+ assert_nil card.reload.accountable.apr+ end+# [Control — CDR loan] Fiskil home loan: -997672.00 stored as +997672.00.test "processor negates a fiskil (CDR) loan balance so the amount owed is stored positive" doloan, ra = link(Loan, provider: "fiskil", balance: "-997672.00")diff --git a/test/models/redbark_item/importer_test.rb b/test/models/redbark_item/importer_test.rbindex 48f57eea02..4111896cf3 100644--- a/test/models/redbark_item/importer_test.rb+++ b/test/models/redbark_item/importer_test.rb@@ -25,7 +25,7 @@ class RedbarkItem::ImporterTest < ActiveSupport::TestCaseimporter = RedbarkItem::Importer.new(redbark_account.redbark_item, redbark_provider: provider)assert_nothing_raised do- importer.send(:import_loan_account_details, [ redbark_account.reload ])+ importer.send(:import_account_details, [ redbark_account.reload ])endassert_equal({ "lendingRate" => "0.0625" }, redbark_account.reload.raw_account_details_payload,@@ -55,7 +55,7 @@ class RedbarkItem::ImporterTest < ActiveSupport::TestCase)travel_to Time.utc(2026, 9, 22, 0, 0, 30) do- importer.send(:import_loan_account_details, [ redbark_account.reload ])+ importer.send(:import_account_details, [ redbark_account.reload ])endassert_equal injected, redbark_account.reload.account_details_fetched_at.utc,@@ -97,7 +97,7 @@ class RedbarkItem::ImporterTest < ActiveSupport::TestCase.returns([])importer = RedbarkItem::Importer.new(item, redbark_provider: provider)- importer.send(:import_loan_account_details, [ first.reload, second.reload ])+ importer.send(:import_account_details, [ first.reload, second.reload ])assert_equal "0.0675", first.reload.raw_account_details_payload["lendingRate"],"the account the retry could serve never got its details stored"@@ -106,9 +106,9 @@ class RedbarkItem::ImporterTest < ActiveSupport::TestCase"an account the retry could not serve was written anyway"end- # Only loans: every other account type would cost a request per sync for a- # field nothing reads.- test "account details are not fetched when no linked account is a loan" do+ # Only loans and credit cards: every other account type would cost a request+ # per sync for a field nothing reads.+ test "account details are not fetched when no linked account is a loan or credit card" doredbark_account = redbark_accounts(:savings_account)family = redbark_account.redbark_item.familyaccount = family.accounts.create!(@@ -121,7 +121,195 @@ class RedbarkItem::ImporterTest < ActiveSupport::TestCaseprovider.expects(:get_account_details).neverimporter = RedbarkItem::Importer.new(redbark_account.redbark_item, redbark_provider: provider)- importer.send(:import_loan_account_details, [ redbark_account.reload ])+ importer.send(:import_account_details, [ redbark_account.reload ])+ end++ # A card's APR comes from the same endpoint.+ test "a credit card's account details are fetched and stamped" do+ redbark_account = redbark_accounts(:savings_account)+ family = redbark_account.redbark_item.family+ account = family.accounts.create!(+ name: "Credit card", balance: 100, currency: "AUD", accountable: CreditCard.new+ )+ redbark_account.ensure_account_provider!(account)++ injected = Time.utc(2026, 11, 20, 9, 0, 0)+ provider = mock+ provider.stubs(:list_connections).returns([])+ provider.expects(:get_account_details)+ .with(account_ids: [ redbark_account.redbark_account_id ])+ .returns([ { accountId: redbark_account.redbark_account_id, lendingRates: [ { rateType: "PURCHASE", rate: "0.1999" } ] } ])+ importer = RedbarkItem::Importer.new(+ redbark_account.redbark_item, redbark_provider: provider, fetched_at: injected+ )++ importer.send(:import_account_details, [ redbark_account.reload ])++ redbark_account.reload+ assert_equal "0.1999", redbark_account.raw_account_details_payload.dig("lendingRates", 0, "rate"),+ "a credit card's details were not stored"+ assert_equal injected, redbark_account.account_details_fetched_at.utc+ end++ # Cards are fetched in a batch of their own, so a card id the endpoint+ # rejects leaves the loans' single batched call alone.+ test "a rejected card id does not push the loans into per-account retries" do+ loan_ra = redbark_accounts(:savings_account)+ item = loan_ra.redbark_item+ family = item.family+ card_ra = item.redbark_accounts.create!(redbark_account_id: "rb_acc_card_1", name: "Card", currency: "AUD")+ loan_ra.ensure_account_provider!(+ family.accounts.create!(name: "Mortgage", balance: 400_000, currency: "AUD", accountable: Loan.new)+ )+ card_ra.ensure_account_provider!(+ family.accounts.create!(name: "Card", balance: 100, currency: "AUD", accountable: CreditCard.new)+ )++ provider = mock+ provider.stubs(:list_connections).returns([])+ provider.expects(:get_account_details)+ .with(account_ids: [ loan_ra.redbark_account_id ]).once+ .returns([ { accountId: loan_ra.redbark_account_id, lendingRate: "0.0675" } ])+ provider.expects(:get_account_details)+ .with(account_ids: [ card_ra.redbark_account_id ]).once+ .raises(Provider::Redbark::Error.new("stale id", :not_found))++ RedbarkItem::Importer.new(item, redbark_provider: provider)+ .send(:import_account_details, [ loan_ra.reload, card_ra.reload ])++ assert_equal "0.0675", loan_ra.reload.raw_account_details_payload["lendingRate"]+ assert_nil card_ra.reload.raw_account_details_payload+ end++ test "a card fetched in the last seven days is not fetched again" do+ redbark_account, item = link_card("rb_acc_card_recent")+ now = Time.utc(2026, 11, 20, 9, 0, 0)+ redbark_account.update!(account_details_fetched_at: now - 6.days)++ provider = mock+ provider.stubs(:list_connections).returns([])+ provider.expects(:get_account_details).never++ RedbarkItem::Importer.new(item, redbark_provider: provider, fetched_at: now)+ .send(:import_account_details, [ redbark_account.reload ])+ end++ test "a card is fetched again once seven days have passed" do+ redbark_account, item = link_card("rb_acc_card_stale")+ now = Time.utc(2026, 11, 20, 9, 0, 0)+ redbark_account.update!(account_details_fetched_at: now - 7.days)++ provider = mock+ provider.stubs(:list_connections).returns([])+ provider.expects(:get_account_details).with(account_ids: [ "rb_acc_card_stale" ]).once.returns([])++ RedbarkItem::Importer.new(item, redbark_provider: provider, fetched_at: now)+ .send(:import_account_details, [ redbark_account.reload ])+ end++ test "a failed card fetch is stamped, logged and not a sync error" do+ redbark_account, item = link_card("rb_acc_card_failing")+ now = Time.utc(2026, 11, 20, 9, 0, 0)+ provider = mock+ provider.stubs(:list_connections).returns([])+ provider.expects(:get_account_details).once.raises(Provider::Redbark::Error.new("stale id", :not_found))+ importer = RedbarkItem::Importer.new(item, redbark_provider: provider, fetched_at: now)++ assert_difference -> { DebugLogEntry.where(source: RedbarkItem::Importer.name).count }, 1 do+ importer.send(:import_account_details, [ redbark_account.reload ])+ RedbarkItem::Importer.new(item, redbark_provider: provider, fetched_at: now + 1.day)+ .send(:import_account_details, [ redbark_account.reload ])+ end++ assert_equal now, redbark_account.reload.account_details_fetched_at.utc, "a failed attempt was not stamped"+ assert_nil redbark_account.raw_account_details_payload+ assert importer.send(:stats)["errors"].blank?, "a card fetch failure was registered as a sync error"+ end++ # The stamp is what the card processor reads as "fetched this window", so a+ # failed attempt must not leave an older payload under a fresh stamp.+ test "a failed card fetch clears an old payload so the APR stays blank" do+ redbark_account, item = link_card("rb_acc_card_old_payload")+ now = Time.utc(2026, 11, 20, 9, 0, 0)+ redbark_account.update!(+ raw_account_details_payload: { "lendingRates" => [ { "rateType" => "PURCHASE", "rate" => "0.1999" } ] },+ account_details_fetched_at: now - 30.days+ )+ provider = mock+ provider.stubs(:list_connections).returns([])+ provider.expects(:get_account_details).once.raises(Provider::Redbark::Error.new("boom", :server_error))++ RedbarkItem::Importer.new(item, redbark_provider: provider, fetched_at: now)+ .send(:import_account_details, [ redbark_account.reload ])+ RedbarkAccount::CreditCardDetailsProcessor.new(redbark_account.reload, as_of: now.to_date).process++ assert_nil redbark_account.current_account.accountable.reload.apr,+ "a payload from before the failed fetch filled the APR"+ assert_nil redbark_account.raw_account_details_payload+ end++ test "a card the provider leaves out is stamped so it waits for the window" do+ redbark_account, item = link_card("rb_acc_card_omitted")+ now = Time.utc(2026, 11, 20, 9, 0, 0)+ redbark_account.update!(raw_account_details_payload: { "lendingRates" => [] }, account_details_fetched_at: now - 30.days)+ provider = mock+ provider.stubs(:list_connections).returns([])+ provider.expects(:get_account_details).once.returns([])++ RedbarkItem::Importer.new(item, redbark_provider: provider, fetched_at: now)+ .send(:import_account_details, [ redbark_account.reload ])++ assert_equal now, redbark_account.reload.account_details_fetched_at.utc+ assert_nil redbark_account.raw_account_details_payload, "an old payload was kept under the new stamp"+ end++ test "a card failure already logged in the window is not logged again" do+ redbark_account, item = link_card("rb_acc_card_repeat")+ provider = mock+ provider.stubs(:list_connections).returns([])+ provider.stubs(:get_account_details).raises(Provider::Redbark::Error.new("stale id", :not_found))++ assert_difference -> { DebugLogEntry.where(source: RedbarkItem::Importer.name).count }, 1 do+ 2.times do+ redbark_account.update_columns(account_details_fetched_at: nil)+ RedbarkItem::Importer.new(item, redbark_provider: provider).send(:import_account_details, [ redbark_account.reload ])+ end+ end+ end++ test "a rejected batch of cards and its per-card retries are each logged once" do+ first, item = link_card("rb_acc_card_a")+ second, = link_card("rb_acc_card_b")+ provider = mock+ provider.stubs(:list_connections).returns([])+ provider.stubs(:get_account_details).raises(Provider::Redbark::Error.new("stale id", :not_found))++ assert_difference -> { DebugLogEntry.where(source: RedbarkItem::Importer.name).count }, 3 do+ 2.times do+ [ first, second ].each { |redbark_account| redbark_account.update_columns(account_details_fetched_at: nil) }+ RedbarkItem::Importer.new(item, redbark_provider: provider).send(:import_account_details, [ first.reload, second.reload ])+ end+ end+ end++ test "a card whose APR is set or locked is not fetched" do+ with_apr = redbark_accounts(:savings_account)+ item = with_apr.redbark_item+ family = item.family+ locked = item.redbark_accounts.create!(redbark_account_id: "rb_acc_card_2", name: "Locked card", currency: "AUD")+ with_apr.ensure_account_provider!(+ family.accounts.create!(name: "Card", balance: 100, currency: "AUD", accountable: CreditCard.new(apr: 12.5))+ )+ locked_account = family.accounts.create!(name: "Locked card", balance: 100, currency: "AUD", accountable: CreditCard.new)+ locked_account.accountable.lock_attr!(:apr)+ locked.ensure_account_provider!(locked_account)++ provider = mock+ provider.stubs(:list_connections).returns([])+ provider.expects(:get_account_details).never++ RedbarkItem::Importer.new(item, redbark_provider: provider)+ .send(:import_account_details, [ with_apr.reload, locked.reload ])endtest "merge_transactions keeps posted rows and refreshes by id" do@@ -217,4 +405,13 @@ class RedbarkItem::ImporterTest < ActiveSupport::TestCaseimporter.send(:import_transactions, redbark_account)end++ def link_card(redbark_account_id)+ item = redbark_accounts(:savings_account).redbark_item+ redbark_account = item.redbark_accounts.create!(redbark_account_id: redbark_account_id, name: "Card", currency: "AUD")+ redbark_account.ensure_account_provider!(+ item.family.accounts.create!(name: "Card", balance: 100, currency: "AUD", accountable: CreditCard.new)+ )+ [ redbark_account, item ]+ endend