Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Read a loan's rate from Redbark's account details (#3956)

jaysbeekayfe0e56e8590e
diff --git a/app/models/plaid_account/liabilities/student_loan_processor.rb b/app/models/plaid_account/liabilities/student_loan_processor.rb
index 205fdb8045..5ecbf9a969 100644
--- a/app/models/plaid_account/liabilities/student_loan_processor.rb
+++ b/app/models/plaid_account/liabilities/student_loan_processor.rb
@@ -48,6 +48,9 @@ class PlaidAccount::Liabilities::StudentLoanProcessor
# origination, or before it, is nil rather than zero: a term of no months
# is not a term, and it would make the loan look amortisable over a
# schedule that cannot exist.
+ #
+ # RedbarkAccount::LoanDetailsProcessor#term_months_between counts a term the
+ # same way; a change to the rule here belongs there too.
def term_months
return nil unless origination_date && expected_payoff_date
diff --git a/app/models/provider/redbark.rb b/app/models/provider/redbark.rb
index fb60ad093c..360db15fd2 100644
--- a/app/models/provider/redbark.rb
+++ b/app/models/provider/redbark.rb
@@ -11,6 +11,8 @@ class Provider::Redbark
# Server-side maximums for limit/offset pagination
ACCOUNTS_PAGE_SIZE = 200
TRANSACTIONS_PAGE_SIZE = 500
+ # The documented cap on `accountIds`, applied after server-side dedup.
+ ACCOUNT_DETAILS_BATCH_SIZE = 100
class Error < StandardError
attr_reader :error_type
@@ -68,6 +70,39 @@ class Provider::Redbark
end
end
+ # Returns product details for the given account ids: the bank's own view of
+ # the product behind the account, including its rates (we-promise/sure#3891).
+ #
+ # Response items: { accountId, productName, depositRate, depositRates,
+ # lendingRate, lendingRates, fees, features, loanDetails }. Rates are decimal
+ # STRINGS expressed as fractions -- "0.0419" is 4.19% -- and carry no
+ # effective date, which is why a detected change is dated the day it was
+ # seen rather than a date the bank supplied.
+ #
+ # Batched at 100 ids, the documented cap, which the API applies AFTER
+ # deduplicating the list. The whole request fails on an id the key does not
+ # own (404) or an account of the wrong category (400), so callers filter
+ # first, the way `get_balances` does; an account the provider has no detail
+ # for is omitted from `data` rather than erroring.
+ #
+ # Responses may be served from a server-side cache for up to 15 minutes, so
+ # two syncs inside that window can legitimately return the same rate.
+ def get_account_details(account_ids:)
+ ids = Array(account_ids).compact.map(&:to_s).uniq
+ return [] if ids.empty?
+
+ ids.each_slice(ACCOUNT_DETAILS_BATCH_SIZE).flat_map do |batch|
+ with_retries("get_account_details") do
+ response = self.class.get(
+ "#{BASE_URL}/account-details",
+ headers: auth_headers,
+ query: { accountIds: batch.join(",") }
+ )
+ handle_response(response)[:data] || []
+ end
+ end
+ end
+
# Returns all transactions for one account within the date range.
# Both connection_id and account_id are required by the API.
# Response items: { id, accountId, accountName, status, date, datetime, postDate,
diff --git a/app/models/redbark_account.rb b/app/models/redbark_account.rb
index e8889bace7..bf5d4f68ac 100644
--- a/app/models/redbark_account.rb
+++ b/app/models/redbark_account.rb
@@ -8,6 +8,7 @@ class RedbarkAccount < ApplicationRecord
if encryption_ready?
encrypts :raw_payload
encrypts :raw_transactions_payload
+ encrypts :raw_account_details_payload
end
belongs_to :redbark_item
diff --git a/app/models/redbark_account/loan_details_processor.rb b/app/models/redbark_account/loan_details_processor.rb
new file mode 100644
index 0000000000..851b7c8a12
--- /dev/null
+++ b/app/models/redbark_account/loan_details_processor.rb
@@ -0,0 +1,313 @@
+# frozen_string_literal: true
+
+# Reads a loan's rate from what the bank reported, and records a change in the
+# one place a loan's rates live: `loans.variable_rate_schedule` (we-promise/sure#3891).
+#
+# THE DATE IS THE DAY IT WAS SEEN, and that is a limitation rather than a
+# choice. `GET /v1/account-details` reports the rate in force right now and
+# carries no effective date and no history -- neither `lendingRate` nor any
+# entry in `lendingRates[]` has one, and the CDR standard behind it does not
+# either. So a change detected on the 21st is recorded as the 21st even if the
+# bank moved it on the 14th. Dating it earlier would be inventing a fact.
+#
+# `as_of` is INJECTED and never read from the clock in here. A sync that spans
+# midnight, a replay, and a test all need the schedule keyed to the date the
+# caller means, and a loan's figures are derived from those keys.
+class RedbarkAccount::LoanDetailsProcessor
+ SOURCE = "redbark"
+
+ attr_reader :redbark_account, :as_of
+
+ def initialize(redbark_account, as_of:)
+ @redbark_account = redbark_account
+ @as_of = as_of
+ end
+
+ def process
+ return unless loan
+ return if details.blank?
+ return unless details_fetched_this_sync?
+
+ apply_loan_terms
+ apply_rate
+ end
+
+ private
+ # A payload the sync did not refresh is a previous answer, not a current
+ # one. Acting on it can record a change that never happened: the fetch
+ # fails, the stored snapshot still holds last week's rate, the user has
+ # since corrected the loan by hand, and the stale figure is written back
+ # over their correction as though the bank had just reported it.
+ #
+ # Keyed to the sync's own date rather than to a duration, because `as_of`
+ # is the only notion of "now" this class is allowed. RedbarkItem::Syncer
+ # reads the clock ONCE and hands the same instant to the import that writes
+ # this stamp and to the processing that supplies `as_of`, so the comparison
+ # below is a clock against itself; two readings would make a sync that
+ # crosses midnight reject the snapshot it had just stored. A second sync on
+ # the same day after a failed fetch re-reads a snapshot that was fresh this
+ # morning, which is harmless: the rate has not moved, so nothing is
+ # recorded.
+ def details_fetched_this_sync?
+ fetched_at = redbark_account.account_details_fetched_at
+ return false if fetched_at.blank?
+
+ fetched_at.to_date == as_of.to_date
+ end
+
+ def account
+ @account ||= redbark_account.current_account
+ end
+
+ def loan
+ return @loan if defined?(@loan)
+
+ @loan = account&.accountable_type == "Loan" ? account.accountable : nil
+ end
+
+ def details
+ @details ||= redbark_account.raw_account_details_payload&.deep_symbolize_keys || {}
+ end
+
+ # The headline rate first, because it is the bank's own answer to "what is
+ # this loan's rate". `lendingRates[]` is a product description: it can carry
+ # several rate types, and `tiers` can split one of those into bands, so a
+ # single figure cannot be pulled from it unless exactly one candidate
+ # survives.
+ def reported_rate
+ return @reported_rate if defined?(@reported_rate)
+
+ @reported_rate = to_percentage(details[:lendingRate]) || single_variable_rate
+ end
+
+ def single_variable_rate
+ rates = details[:lendingRates]
+
+ unless rates.is_a?(Array)
+ # Not an error: a deposit account has no lending rates, and a bank that
+ # reports none for a loan is "nothing to say", not "malformed". Only a
+ # shape that is neither absent nor an array is worth a line.
+ capture("Redbark account details carried no usable lendingRates", shape: rates.class.name) unless rates.nil?
+ return nil
+ end
+
+ candidates = rates.select { |entry| entry.is_a?(Hash) && entry[:rateType].to_s.casecmp("VARIABLE").zero? }
+ # A tiered rate is several rates wearing one entry: which band applies
+ # depends on the balance, and the payload does not say which one the
+ # account sits in.
+ candidates = candidates.reject { |entry| Array(entry[:tiers]).any? }
+
+ if candidates.size > 1
+ capture("Redbark reported several variable rates; recording none", candidate_count: candidates.size)
+ return nil
+ end
+
+ to_percentage(candidates.first&.dig(:rate))
+ end
+
+ # The API reports fractions: "0.0675" is 6.75%. The schedule and
+ # `interest_rate` are both percentages.
+ def to_percentage(value)
+ return nil if value.blank?
+
+ decimal = BigDecimal(value.to_s)
+ # THREE decimal places, so a rate reads the same on every sync and what
+ # is stored is what is compared. A bank reporting 0.064994 one sync and
+ # 0.064996 the next would otherwise record a new row each time for a
+ # movement of a hundredth of a basis point.
+ rate = (decimal * 100).round(3)
+ # The loan form caps a rate at Loan::MAX_INTEREST_RATE, and the model does
+ # not check a schedule written any other way. A bank reporting 150% has
+ # sent something other than a rate.
+ return rate if rate.between?(0, Loan::MAX_INTEREST_RATE)
+
+ capture("Redbark reported a rate outside 0..#{Loan::MAX_INTEREST_RATE}%; ignoring it", value: value.to_s)
+ nil
+ rescue ArgumentError, TypeError
+ capture("Redbark reported an unparseable rate", value: value.to_s)
+ nil
+ end
+
+ def apply_rate
+ return if reported_rate.nil?
+
+ adopt_rate_type_if_blank
+
+ unless loan.variable_rate_type?
+ # A fixed loan's rate does not move, so a bank reporting a different one
+ # is a disagreement to surface, not a change to record. Nothing is
+ # written -- not the schedule, not `interest_rate`, not `rate_type`.
+ if loan.interest_rate.present? && BigDecimal(loan.interest_rate.to_s) != reported_rate
+ capture(
+ "Redbark reported a rate for a fixed loan; recording nothing",
+ loan_id: loan.id, reported: reported_rate.to_s, recorded: loan.interest_rate.to_s
+ )
+ end
+ return
+ end
+
+ return if record_first_sighting
+ record_change
+ end
+
+ # A loan whose rate was never recorded is not a loan whose rate just moved.
+ # Setting the base rate is the honest reading; a schedule row would claim a
+ # change happened on a day nothing is known to have happened.
+ #
+ # TRUE WHETHER OR NOT THE WRITE STUCK, deliberately. A blank rate that stays
+ # blank is either locked, which the user asked for and which must not be
+ # routed around through the schedule, or refused, in which case the rate is
+ # still blank next sync, so the next sync is a first sighting again and
+ # retries it. Falling through to `record_change` would date a change on a
+ # day nothing moved.
+ def record_first_sighting
+ return false if loan.interest_rate.present?
+
+ write({ interest_rate: reported_rate })
+ true
+ end
+
+ def record_change
+ in_force = loan.current_variable_rate(as_of)
+ return if in_force.present? && BigDecimal(in_force.to_s) == reported_rate
+
+ schedule = (loan.variable_rate_schedule || {}).stringify_keys
+ key = as_of.to_date.iso8601
+ return if schedule.key?(key) && BigDecimal(schedule[key].to_s) == reported_rate
+
+ write({ variable_rate_schedule: schedule.merge(key => reported_rate.to_s) })
+ end
+
+ # `rate_type` is blank on a loan nobody has classified. A bank calling its
+ # own product VARIABLE is better evidence than silence, and without this the
+ # rate is read and then dropped, since only a variable loan keeps a schedule.
+ def adopt_rate_type_if_blank
+ return if loan.rate_type.present?
+ return unless bank_says_variable?
+
+ write({ rate_type: "variable" })
+ end
+
+ def bank_says_variable?
+ Array(details[:lendingRates]).any? do |entry|
+ entry.is_a?(Hash) && entry[:rateType].to_s.casecmp("VARIABLE").zero?
+ end
+ end
+
+ # Each filled only when blank: these describe the loan as it was written,
+ # and a value already on the record is either the user's or an earlier
+ # provider's. `enrich_attributes` skips locked attributes on its own.
+ def apply_loan_terms
+ terms = details[:loanDetails]
+ return unless terms.is_a?(Hash)
+
+ attrs = {}
+ attrs[:start_date] = parse_date(terms[:originalStartDate]) if loan.start_date.blank?
+ attrs[:initial_balance] = parse_decimal(terms[:originalLoanAmount]) if loan.initial_balance.blank?
+
+ if loan.term_months.blank?
+ months = term_months_between(terms[:originalStartDate], terms[:loanEndDate])
+ attrs[:term_months] = months if months
+ end
+
+ attrs.compact!
+ write(attrs) if attrs.any?
+ end
+
+ def term_months_between(start_value, end_value)
+ from = parse_date(start_value)
+ to = parse_date(end_value)
+ return nil if from.nil? || to.nil? || to <= from
+
+ months = ((to.year - from.year) * 12) + (to.month - from.month)
+ # An end date before the origination day in its month has not reached the
+ # anniversary, so that month is not complete (as in
+ # PlaidAccount::Liabilities::StudentLoanProcessor#term_months).
+ months -= 1 if from + months.months > to
+ return nil unless months.positive?
+
+ # The longest term the loan form accepts. A bank reporting an end date
+ # centuries out is reporting a placeholder, and a term of 13,200 months
+ # is not something to store as though it were the loan's.
+ months <= Loan::Simulator::MAX_PERIODS ? months : nil
+ end
+
+ def parse_date(value)
+ return nil if value.blank?
+
+ Date.parse(value.to_s)
+ rescue Date::Error
+ capture("Redbark reported an unparseable date", value: value.to_s)
+ nil
+ end
+
+ def parse_decimal(value)
+ return nil if value.blank?
+
+ amount = BigDecimal(value.to_s)
+ # Only a positive finite figure is a principal: Loan#original_balance
+ # reads a zero or negative one as unrecorded, so storing it would show the
+ # form a balance the loan itself ignores.
+ amount if amount.finite? && amount.positive?
+ rescue ArgumentError, TypeError
+ nil
+ end
+
+ # Every write goes through Enrichable: it skips locked attributes, records
+ # provenance as a DataEnrichment, and calls `save` rather than `save!`, so a
+ # value the model refuses -- a rate outside 0..100, say -- returns false
+ # instead of raising and taking the sync with it.
+ #
+ # `false` alone is NOT a failure. Enrichable also returns it when every
+ # attribute was locked or already held the value, which are the ordinary
+ # quiet paths (rows 3 and 5). Only a populated `errors` distinguishes a
+ # refusal from a no-op, and logging on `false` alone would put a warning in
+ # the debug log every time a user's lock did exactly its job.
+ def write(attrs)
+ return if attrs.blank?
+
+ # Enrichable logs the DataEnrichment before it saves, and a refused save
+ # does not roll that row back. The outer transaction does, so provenance
+ # never says Redbark supplied a value the loan rejected.
+ ActiveRecord::Base.transaction do
+ loan.enrich_attributes(attrs, source: SOURCE)
+ raise ActiveRecord::Rollback if loan.errors.any?
+ end
+ return if loan.errors.empty?
+
+ capture(
+ "Redbark loan detail refused by the model",
+ loan_id: loan.id,
+ attributes: attrs.keys.map(&:to_s),
+ errors: loan.errors.full_messages
+ )
+
+ # A refusal is not tidied up by Enrichable: it assigns, calls `save`, and
+ # when `save` returns false the REJECTED VALUES ARE STILL ON THE LOAN and
+ # its errors are still populated. Terms are applied before the rate, so a
+ # bank reporting an absurd `loanEndDate` would leave an out-of-range
+ # `term_months` assigned, the rate write would then be refused for the
+ # term rather than for the rate, and the loan would lose a rate change it
+ # had every right to. The log would name the rate attributes and carry
+ # the term's errors, which is how it would be misread.
+ #
+ # Clearing the errors matters on its own: `enrich_attributes` returns
+ # early without saving when every attribute is locked or unchanged, so a
+ # later no-op write would find these errors still sitting there and
+ # report a refusal that did not happen.
+ loan.restore_attributes(attrs.keys.map(&:to_s))
+ loan.errors.clear
+ 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,
+ metadata: metadata.merge(redbark_account_id: redbark_account.id)
+ )
+ end
+end
diff --git a/app/models/redbark_account/processor.rb b/app/models/redbark_account/processor.rb
index a136f4ac12..4a915c0ada 100644
--- a/app/models/redbark_account/processor.rb
+++ b/app/models/redbark_account/processor.rb
@@ -3,10 +3,13 @@
class RedbarkAccount::Processor
include RedbarkAccount::DataHelpers
- attr_reader :redbark_account
+ attr_reader :redbark_account, :as_of
- def initialize(redbark_account)
+ # `as_of` is the sync's own date, injected by the caller rather than read
+ # here: a detected rate change is keyed by it (we-promise/sure#3891).
+ def initialize(redbark_account, as_of: Date.current)
@redbark_account = redbark_account
+ @as_of = as_of
end
def process
@@ -29,6 +32,11 @@ class RedbarkAccount::Processor
Rails.logger.warn "RedbarkAccount::Processor - No transactions payload to process"
end
+ # A loan's rate, read from what the bank reported. After transactions, so a
+ # 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
+
# Trigger immediate UI refresh so entries appear in the activity feed
account.broadcast_sync_complete
Rails.logger.info "RedbarkAccount::Processor - Broadcast sync complete for account #{account.id}"
diff --git a/app/models/redbark_item.rb b/app/models/redbark_item.rb
index a219bc86f8..8dd773293b 100644
--- a/app/models/redbark_item.rb
+++ b/app/models/redbark_item.rb
@@ -32,14 +32,19 @@ class RedbarkItem < ApplicationRecord
end
# Import data from provider API
- def import_latest_redbark_data(sync: nil)
+ # `fetched_at` is the sync's own clock, injected so that the account-details
+ # snapshot is stamped with the same instant the processing phase dates its
+ # findings by (see RedbarkItem::Syncer). A caller outside a sync -- the
+ # manual refresh in RedbarkItemsController -- stamps the real fetch time,
+ # which is what it means.
+ def import_latest_redbark_data(sync: nil, fetched_at: Time.current)
provider = redbark_provider
unless provider
Rails.logger.error "RedbarkItem #{id} - Cannot import: provider is not configured"
raise StandardError, I18n.t("redbark_items.errors.provider_not_configured")
end
- RedbarkItem::Importer.new(self, redbark_provider: provider, sync: sync).import
+ RedbarkItem::Importer.new(self, redbark_provider: provider, sync: sync, fetched_at: fetched_at).import
rescue => e
DebugLogEntry.capture(
category: "provider_sync",
@@ -55,13 +60,18 @@ class RedbarkItem < ApplicationRecord
end
# Process linked accounts after data import
- def process_accounts
+ #
+ # `as_of` is captured ONCE here and passed down, so every account in one sync
+ # dates its findings the same way. A sync that starts at 23:59 must not write
+ # one loan's detected rate change under today and the next loan's under
+ # tomorrow (we-promise/sure#3891).
+ def process_accounts(as_of: Date.current)
return [] if redbark_accounts.empty?
results = []
linked_redbark_accounts.includes(account_provider: :account).each do |redbark_account|
begin
- result = RedbarkAccount::Processor.new(redbark_account).process
+ result = RedbarkAccount::Processor.new(redbark_account, as_of: as_of).process
results << { redbark_account_id: redbark_account.id, success: true, result: result }
rescue => e
DebugLogEntry.capture(
diff --git a/app/models/redbark_item/importer.rb b/app/models/redbark_item/importer.rb
index 71919006ca..e72f909ff4 100644
--- a/app/models/redbark_item/importer.rb
+++ b/app/models/redbark_item/importer.rb
@@ -5,12 +5,16 @@ class RedbarkItem::Importer
include RedbarkAccount::DataHelpers
include CurrencyNormalizable
- attr_reader :redbark_item, :redbark_provider, :sync
+ attr_reader :redbark_item, :redbark_provider, :sync, :fetched_at
- def initialize(redbark_item, redbark_provider:, sync: nil)
+ # `fetched_at` stamps the account-details snapshot. It is injected rather
+ # than read here so that one sync's fetch and its processing share a clock;
+ # see RedbarkItem::Syncer.
+ def initialize(redbark_item, redbark_provider:, sync: nil, fetched_at: Time.current)
@redbark_item = redbark_item
@redbark_provider = redbark_provider
@sync = sync
+ @fetched_at = fetched_at
end
def import
@@ -21,7 +25,10 @@ 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.
- linked_accounts = redbark_item.linked_redbark_accounts.to_a
+ # `account_provider: :account` is preloaded because the loan filter in
+ # import_loan_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
Rails.logger.info "RedbarkItem::Importer - Found #{linked_accounts.count} linked accounts to process"
@@ -30,6 +37,7 @@ class RedbarkItem::Importer
end
import_balances(linked_accounts)
+ import_loan_account_details(linked_accounts)
# Store import stats on the item as the raw snapshot
redbark_item.upsert_redbark_snapshot!(stats)
@@ -194,6 +202,74 @@ class RedbarkItem::Importer
end
end
+ # 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.
+ #
+ # 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
+ account_ids = eligible_accounts.map(&:redbark_account_id).compact
+ return if account_ids.empty?
+
+ begin
+ details_by_id = fetch_account_details_with_fallback(account_ids)
+ .index_by { |detail| detail[:accountId].to_s }
+
+ eligible_accounts.each do |redbark_account|
+ detail = details_by_id[redbark_account.redbark_account_id]
+ # An account the provider has no detail for is omitted from `data`
+ # rather than erroring, so leave the last payload in place -- and
+ # leave the stamp alone with it, so the processor knows the snapshot
+ # is not from this sync.
+ next if detail.blank?
+
+ redbark_account.update!(
+ raw_account_details_payload: detail,
+ account_details_fetched_at: fetched_at
+ )
+ stats["account_details_updated"] = stats.fetch("account_details_updated", 0) + 1
+ end
+ rescue Provider::Redbark::AuthenticationError
+ raise
+ rescue => e
+ capture_failure("Account details fetch failed; keeping previous details", e)
+ register_error(e, context: "account_details")
+ end
+ 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)
+ stats["api_requests"] = stats.fetch("api_requests", 0) + 1
+ redbark_provider.get_account_details(account_ids: account_ids)
+ rescue Provider::Redbark::AuthenticationError
+ raise
+ rescue Provider::Redbark::Error => e
+ raise 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)
+
+ account_ids.flat_map do |account_id|
+ begin
+ stats["api_requests"] = stats.fetch("api_requests", 0) + 1
+ redbark_provider.get_account_details(account_ids: [ account_id ])
+ rescue Provider::Redbark::AuthenticationError
+ raise
+ rescue Provider::Redbark::Error => account_error
+ capture_failure("Account details fetch failed for account; keeping previous details", account_error, account_id: account_id)
+ []
+ end
+ end
+ end
+
# The balances endpoint rejects the WHOLE batch when any requested id is
# unknown (404) or non-banking (400), so exclude accounts that no longer
# exist upstream and accounts on non-banking connections up front.
diff --git a/app/models/redbark_item/syncer.rb b/app/models/redbark_item/syncer.rb
index e086f3c2db..1f9997d69b 100644
--- a/app/models/redbark_item/syncer.rb
+++ b/app/models/redbark_item/syncer.rb
@@ -12,9 +12,18 @@ class RedbarkItem::Syncer
def perform_sync(sync)
Rails.logger.info "RedbarkItem::Syncer - Starting sync for item #{redbark_item.id}"
+ # ONE clock for the whole sync. The import stamps the account-details
+ # snapshot with it, and the processing phase dates its findings by it, so
+ # the freshness gate in RedbarkAccount::LoanDetailsProcessor compares a
+ # clock against itself. Reading `Time.current` in the import and
+ # `Date.current` again in the processing gives a sync that fetches at
+ # 23:59 and processes at 00:00 two different dates, and the processor then
+ # discards the snapshot this very sync just stored.
+ synced_at = Time.current
+
# Phase 1: Import data from provider API
sync.update!(status_text: I18n.t("redbark_items.sync.status.importing")) if sync.respond_to?(:status_text)
- import_stats = redbark_item.import_latest_redbark_data(sync: sync)
+ import_stats = redbark_item.import_latest_redbark_data(sync: sync, fetched_at: synced_at)
# Phase 2: Collect setup statistics
finalize_setup_counts(sync)
@@ -24,7 +33,7 @@ class RedbarkItem::Syncer
if linked_redbark_accounts.any?
sync.update!(status_text: I18n.t("redbark_items.sync.status.processing")) if sync.respond_to?(:status_text)
mark_import_started(sync)
- redbark_item.process_accounts
+ redbark_item.process_accounts(as_of: synced_at.to_date)
# Phase 4: Schedule balance calculations
sync.update!(status_text: I18n.t("redbark_items.sync.status.calculating")) if sync.respond_to?(:status_text)
diff --git a/db/migrate/20261003090000_add_raw_account_details_payload_to_redbark_accounts.rb b/db/migrate/20261003090000_add_raw_account_details_payload_to_redbark_accounts.rb
new file mode 100644
index 0000000000..baedcae6fb
--- /dev/null
+++ b/db/migrate/20261003090000_add_raw_account_details_payload_to_redbark_accounts.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+# Issue #142 (L45), phase 1. `GET /v1/account-details` is the only Redbark
+# endpoint that reports a loan's rate, and nothing in Sure called it. The
+# response is kept per account, beside the two payloads already stored the same
+# way (`raw_payload`, `raw_transactions_payload`), so the processor works from
+# what the bank actually sent rather than from a value parsed at fetch time.
+#
+# Nullable with no backfill: an account that has never had a details fetch, and
+# one whose fetch failed, are both "nothing reported" and the processor treats
+# them alike.
+class AddRawAccountDetailsPayloadToRedbarkAccounts < ActiveRecord::Migration[8.1]
+ def change
+ add_column :redbark_accounts, :raw_account_details_payload, :jsonb
+ # WHEN the payload was fetched, not just what it said. A stored snapshot
+ # that this sync did not refresh is last week's answer, and processing it
+ # as though the bank had just reported it can record a rate change that
+ # never happened -- back to a rate the user has since corrected by hand.
+ add_column :redbark_accounts, :account_details_fetched_at, :datetime
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index baafbbe2c1..8506a2a8c4 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -2186,6 +2186,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_15_090000) do
end
create_table "redbark_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.datetime "account_details_fetched_at"
t.string "account_status"
t.string "account_type"
t.string "connection_id"
@@ -2196,6 +2197,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_15_090000) do
t.jsonb "institution_metadata"
t.string "name", null: false
t.string "provider"
+ t.jsonb "raw_account_details_payload"
t.jsonb "raw_payload"
t.jsonb "raw_transactions_payload"
t.string "redbark_account_id", null: false
diff --git a/test/models/redbark_account/loan_details_processor_test.rb b/test/models/redbark_account/loan_details_processor_test.rb
new file mode 100644
index 0000000000..6f93a2c4b1
--- /dev/null
+++ b/test/models/redbark_account/loan_details_processor_test.rb
@@ -0,0 +1,518 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+# we-promise/sure#3891: a loan's rate, read from what the bank reported.
+#
+# The rows numbered below are the acceptance rows of that issue. Every rate in
+# a payload is a FRACTION as a string, the way
+# `/v1/account-details` reports it: "0.0675" is 6.75%.
+class RedbarkAccount::LoanDetailsProcessorTest < ActiveSupport::TestCase
+ include ActiveJob::TestHelper
+
+ setup do
+ @redbark_account = redbark_accounts(:savings_account)
+ @family = @redbark_account.redbark_item.family
+ @as_of = Date.new(2026, 9, 21)
+
+ @account = @family.accounts.create!(
+ name: "Mortgage",
+ balance: 400_000,
+ currency: "AUD",
+ accountable: Loan.new(rate_type: "variable", interest_rate: 6.25, term_months: 360, start_date: Date.new(2024, 1, 1))
+ )
+ @loan = @account.accountable
+
+ @redbark_account.ensure_account_provider!(@account)
+ @redbark_account.reload
+ end
+
+ # Row 1: the detection that is the whole point of the slice.
+ test "a reported rate that differs from the rate in force is recorded on the sync date" do
+ detail lendingRate: "0.0675"
+
+ process
+
+ assert_equal({ "2026-09-21" => BigDecimal("6.75") }, rates,
+ "the detected rate was not recorded against the injected sync date")
+ end
+
+ # Row 13: the date is the caller's, not the clock's. Travelling the clock
+ # away from `as_of` is the only way to tell the two apart.
+ test "the row is keyed by the injected date, never by today" do
+ detail lendingRate: "0.0675"
+
+ travel_to Date.new(2026, 12, 25) do
+ process
+ end
+
+ assert_equal [ "2026-09-21" ], schedule.keys,
+ "the processor read the clock instead of the date it was given"
+ end
+
+ # Row 2: the same payload on two syncs is one change, not two -- and the
+ # second must not write to the loan at all.
+ test "the same reported rate twice records one row and writes once" do
+ detail lendingRate: "0.0675"
+
+ assert_difference -> { DataEnrichment.where(enrichable: @loan).count }, 1 do
+ process
+ end
+
+ # The second sync REFRESHES the snapshot -- same payload, new stamp. Without
+ # this the freshness gate stops the second pass and the dedup this row is
+ # named for is never reached, so the test would pass with the dedup deleted.
+ detail lendingRate: "0.0675", fetched_at: (@as_of + 1).in_time_zone
+
+ assert_no_difference -> { DataEnrichment.where(enrichable: @loan).count } do
+ RedbarkAccount::LoanDetailsProcessor.new(@redbark_account.reload, as_of: @as_of + 1).process
+ end
+
+ assert_equal 1, schedule.size, "a second sync recorded the same rate again"
+ end
+
+ # Row 3.
+ test "a reported rate equal to the rate in force records nothing" do
+ detail lendingRate: "0.0625"
+
+ process
+
+ assert_empty schedule, "a rate that had not moved was recorded as a change"
+ end
+
+ # Rows 4 and 10: a fixed loan's rate does not move, so a bank disagreeing is
+ # something to surface rather than something to write.
+ test "a different rate on a fixed loan writes nothing and is logged" do
+ @loan.update!(rate_type: "fixed")
+ detail lendingRate: "0.0675"
+
+ assert_difference -> { DebugLogEntry.count }, 1 do
+ process
+ end
+
+ @loan.reload
+ assert_empty schedule
+ assert_equal 6.25, @loan.interest_rate.to_f, "a fixed loan's base rate was overwritten"
+ assert_equal "fixed", @loan.rate_type
+ end
+
+ # Row 5: a hand-edited schedule stops detection for that loan. The lock is
+ # what the form sets when a user edits the rows.
+ test "a locked schedule is not added to" do
+ @loan.lock_attr!(:variable_rate_schedule)
+ detail lendingRate: "0.0675"
+
+ process
+
+ assert_empty schedule, "a locked schedule was written by the provider"
+ end
+
+ # Row 6, second half: no headline rate, one VARIABLE entry -> use it.
+ test "a single variable entry is used when there is no headline rate" do
+ detail lendingRates: [ { "rateType" => "VARIABLE", "rate" => "0.0699" } ]
+
+ process
+
+ assert_equal({ "2026-09-21" => BigDecimal("6.99") }, rates)
+ end
+
+ # Row 6, first half: several candidates -> record nothing, say so.
+ test "several variable entries record nothing and are logged" do
+ detail lendingRates: [
+ { "rateType" => "VARIABLE", "rate" => "0.0699" },
+ { "rateType" => "VARIABLE", "rate" => "0.0725" }
+ ]
+
+ assert_difference -> { DebugLogEntry.count }, 1 do
+ process
+ end
+
+ assert_empty schedule
+ end
+
+ # Amendment correction 6: a tiered rate is several rates wearing one entry,
+ # and the payload does not say which band the account sits in.
+ test "a tiered variable entry records nothing" do
+ detail lendingRates: [ {
+ "rateType" => "VARIABLE", "rate" => "0.0699",
+ "tiers" => [ { "name" => "Balance tier", "minimumValue" => 0, "maximumValue" => 250_000 } ]
+ } ]
+
+ process
+
+ assert_empty schedule, "a rate that applies to one balance band was recorded as the loan's rate"
+ end
+
+ # Rows 12a-c: a loan whose rate was never recorded is not a loan whose rate
+ # just moved.
+ test "a first sighting sets the base rate and records no change" do
+ @loan.update!(interest_rate: nil)
+ detail lendingRate: "0.0675"
+
+ process
+
+ @loan.reload
+ assert_equal 6.75, @loan.interest_rate.to_f
+ assert_empty schedule, "a first sighting invented a change that never happened"
+ end
+
+ test "a first sighting leaves a locked base rate untouched" do
+ @loan.update!(interest_rate: nil)
+ @loan.lock_attr!(:interest_rate)
+ detail lendingRate: "0.0675"
+
+ process
+
+ assert_nil @loan.reload.interest_rate
+ assert_empty schedule, "a locked blank rate was routed around through the schedule"
+ end
+
+ # A refused first sighting is not a stalled loan. The rate is still blank, so
+ # the next sync is a first sighting again and retries the base rate -- it
+ # must not fall through to recording a change dated on a day nothing moved.
+ test "a refused first sighting writes no schedule row and is retried next sync" do
+ @loan.update!(interest_rate: nil)
+ # Any validation failure refuses the whole save; a future start date is
+ # one the model rejects without touching the rate.
+ @loan.update_columns(start_date: Date.new(3000, 1, 1))
+ detail lendingRate: "0.0675"
+
+ assert_difference -> { DebugLogEntry.count }, 1 do
+ process
+ end
+
+ assert_nil @loan.reload.interest_rate, "the refused base rate was stored"
+ assert_empty schedule, "a refused first sighting was recorded as a change instead"
+
+ # The next sync loads the loan afresh; reloading stands in for that.
+ @loan.update_columns(start_date: Date.new(2024, 1, 1))
+ @redbark_account.reload
+ process
+
+ assert_equal 6.75, @loan.reload.interest_rate.to_f, "the first sighting was not retried"
+ assert_empty schedule, "the retried first sighting recorded a change"
+ end
+
+ # Row 11.
+ test "a blank rate type becomes variable when the bank calls the product variable" do
+ @loan.update!(rate_type: nil, interest_rate: nil)
+ detail lendingRates: [ { "rateType" => "VARIABLE", "rate" => "0.0699" } ]
+
+ process
+
+ @loan.reload
+ assert_equal "variable", @loan.rate_type
+ assert_equal 6.99, @loan.interest_rate.to_f
+ end
+
+ # Row 17: provenance, so a user can see where a row came from.
+ test "a detected change records its provenance as redbark" do
+ detail lendingRate: "0.0675"
+
+ process
+
+ enrichment = DataEnrichment.find_by(enrichable: @loan, attribute_name: "variable_rate_schedule")
+ assert_not_nil enrichment, "no provenance was recorded for the detected change"
+ assert_equal "redbark", enrichment.source
+ end
+
+ # Row 8.
+ test "loan terms are filled only where blank" do
+ @loan.update!(start_date: nil, term_months: nil, initial_balance: nil)
+ detail(
+ lendingRate: "0.0625",
+ loanDetails: {
+ "originalStartDate" => "2020-03-15", "loanEndDate" => "2050-03-15",
+ "originalLoanAmount" => "512000.00"
+ }
+ )
+
+ process
+
+ @loan.reload
+ assert_equal Date.new(2020, 3, 15), @loan.start_date
+ assert_equal 360, @loan.term_months
+ assert_equal 512_000, @loan.initial_balance.to_f
+ end
+
+ test "loan terms already set are left alone" do
+ @loan.update!(start_date: Date.new(2019, 1, 1), term_months: 240, initial_balance: 100)
+ detail(
+ lendingRate: "0.0625",
+ loanDetails: {
+ "originalStartDate" => "2020-03-15", "loanEndDate" => "2050-03-15",
+ "originalLoanAmount" => "512000.00"
+ }
+ )
+
+ process
+
+ @loan.reload
+ assert_equal Date.new(2019, 1, 1), @loan.start_date
+ assert_equal 240, @loan.term_months
+ assert_equal 100, @loan.initial_balance.to_f
+ end
+
+ # A snapshot this sync did not refresh is a previous answer, not a current
+ # one. Acting on it writes last week's rate back over a correction the user
+ # has made since -- as though the bank had just reported it.
+ test "a snapshot from an earlier sync is not acted on" do
+ detail lendingRate: "0.0675", fetched_at: (@as_of - 3).in_time_zone
+
+ process
+
+ assert_empty schedule,
+ "a stale snapshot was recorded as though the bank had just reported it"
+ end
+
+ # The boundary, one second wide: a snapshot stamped at 23:59:59 yesterday is
+ # a previous sync's answer even though it is barely a moment old. Nothing in
+ # the gate measures age -- it asks which sync stored it -- and the same
+ # boundary is why RedbarkItem::Syncer now hands one clock to both phases.
+ test "a snapshot stamped a second before the sync date is not acted on" do
+ detail lendingRate: "0.0675", fetched_at: (@as_of - 1).end_of_day
+
+ process
+
+ assert_empty schedule,
+ "a snapshot from the previous day was treated as this sync's"
+ end
+
+ test "a snapshot refreshed today is acted on" do
+ detail lendingRate: "0.0675", fetched_at: @as_of.in_time_zone
+
+ process
+
+ assert_equal({ "2026-09-21" => BigDecimal("6.75") }, rates)
+ end
+
+ # A bank reporting an end date centuries out is reporting a placeholder. The
+ # term is not stored, and the rate still lands.
+ test "an implausible term is not stored and does not cost the loan its rate" do
+ @loan.update!(start_date: nil, initial_balance: nil, term_months: nil)
+ detail(
+ lendingRate: "0.0675",
+ loanDetails: { "originalStartDate" => "1900-01-01", "loanEndDate" => "3000-01-01" }
+ )
+
+ process
+
+ assert_nil @loan.reload.term_months,
+ "a term beyond Loan::Simulator::MAX_PERIODS (#{Loan::Simulator::MAX_PERIODS}) was stored"
+ assert_equal({ "2026-09-21" => BigDecimal("6.75") }, rates)
+ end
+
+ # The longest term the form accepts is kept: the cap is a boundary, not a
+ # blanket refusal of long loans.
+ test "a term at the form's limit is stored" do
+ @loan.update!(start_date: nil, initial_balance: nil, term_months: nil)
+ detail(
+ lendingRate: "0.0675",
+ loanDetails: { "originalStartDate" => "1990-01-01", "loanEndDate" => "2090-01-01" }
+ )
+
+ process
+
+ assert_equal Loan::Simulator::MAX_PERIODS, @loan.reload.term_months
+ end
+
+ # A term is whole months. An end date before the origination day in its month
+ # has not reached the anniversary, so the last month is not complete: counting
+ # it overstates the term by one, as Plaid's student loan term does not.
+ test "a term stops at the last complete month" do
+ @loan.update!(start_date: nil, initial_balance: nil, term_months: nil)
+ detail(
+ lendingRate: "0.0675",
+ loanDetails: { "originalStartDate" => "2024-01-15", "loanEndDate" => "2025-01-10" }
+ )
+
+ process
+
+ assert_equal 11, @loan.reload.term_months,
+ "an end date four days short of the anniversary was counted as a full twelfth month"
+ end
+
+ test "a term ending on the anniversary day counts that month" do
+ @loan.update!(start_date: nil, initial_balance: nil, term_months: nil)
+ detail(
+ lendingRate: "0.0675",
+ loanDetails: { "originalStartDate" => "2024-01-15", "loanEndDate" => "2025-01-15" }
+ )
+
+ process
+
+ assert_equal 12, @loan.reload.term_months
+ end
+
+ # `Loan#original_balance` reads a zero or negative initial balance as
+ # unrecorded and falls back to the first valuation, while the form would still
+ # show the stored figure. A principal that is not a positive finite number is
+ # not stored at all.
+ test "a principal that is not positive is not stored" do
+ [ "0", "-400000", "NaN", "Infinity" ].each do |amount|
+ @loan.update!(initial_balance: nil)
+ detail(lendingRate: "0.0675", loanDetails: { "originalLoanAmount" => amount })
+
+ process
+
+ assert_nil @loan.reload.initial_balance, "an originalLoanAmount of #{amount} was stored as the principal"
+ end
+ end
+
+ # `enrich_attributes` logs the enrichment inside its transaction and then
+ # calls `save`, which returns false on a refusal without rolling back, so the
+ # row that says Redbark supplied the value would outlive a loan that rejected
+ # it.
+ test "a refused write leaves no provenance behind" do
+ @loan.update_columns(start_date: nil)
+ @account.set_opening_anchor_balance(balance: 400_000, date: Date.new(2024, 1, 1))
+ detail(lendingRate: "0.0675", loanDetails: { "originalStartDate" => "3000-01-01" })
+
+ assert_no_difference -> { DataEnrichment.where(enrichable: @loan, attribute_name: "start_date").count } do
+ process
+ end
+ end
+
+ # Terms are applied BEFORE the rate, and `enrich_attributes` leaves a refused
+ # value assigned on the loan. A start date in the future is refused by the
+ # model, and left assigned it would make the rate write that follows fail
+ # for the start date it was still carrying -- the loan would lose a rate
+ # change it had every right to. Asserts the rate lands, which is the thing
+ # the refusal was taking away.
+ test "a start date the model refuses does not cost the loan its rate" do
+ @loan.update_columns(start_date: nil)
+ # With no start date the model measures a rate change against the account's
+ # opening date, which would otherwise be today and refuse the 21st.
+ @account.set_opening_anchor_balance(balance: 400_000, date: Date.new(2024, 1, 1))
+ detail(lendingRate: "0.0675", loanDetails: { "originalStartDate" => "3000-01-01" })
+
+ process
+
+ assert_nil @loan.reload.start_date, "a start date in the future was stored"
+ assert_equal({ "2026-09-21" => BigDecimal("6.75") }, rates,
+ "the rate was refused for the start date the loan was still carrying")
+ end
+
+ # The other half: a refusal must not leave its ERRORS behind for the next
+ # write to find. `enrich_attributes` returns early WITHOUT saving when every
+ # attribute is locked, so the write that follows a refusal never clears them
+ # itself -- it reports the previous attribute's errors as its own refusal.
+ #
+ # The loan here has a LOCKED schedule, so the rate write is a genuine no-op:
+ # exactly one thing was refused, so exactly one line belongs in the log.
+ test "a refusal does not leave its errors for a locked write to report" do
+ @loan.update_columns(start_date: nil)
+ @account.set_opening_anchor_balance(balance: 400_000, date: Date.new(2024, 1, 1))
+ @loan.lock_attr!(:variable_rate_schedule)
+ detail(lendingRate: "0.0675", loanDetails: { "originalStartDate" => "3000-01-01" })
+
+ assert_difference -> { DebugLogEntry.count }, 1 do
+ process
+ end
+
+ assert_empty schedule, "a locked schedule was written by the provider"
+ end
+
+ # The processor reads rates to three decimals. Comparing the four a bank
+ # sends against three stored would make an unchanged rate look changed EVERY
+ # sync, and the loan would gain a row a day for ever.
+ test "a rate with more precision than the loan stores does not re-record every sync" do
+ @loan.update!(variable_rate_schedule: { "2026-09-01" => 6.499 })
+ detail lendingRate: "0.064994"
+
+ process
+
+ assert_equal [ "2026-09-01" ], schedule.keys,
+ "the same rate was recorded again because it was compared at a precision the loan does not keep"
+ end
+
+ # Row 14: an account the provider reported nothing for.
+ test "no payload writes nothing and does not raise" do
+ @redbark_account.update!(raw_account_details_payload: nil)
+
+ assert_nothing_raised { process }
+ assert_empty schedule
+ end
+
+ # Row 16: a shape that is neither absent nor an array.
+ test "a malformed lendingRates shape writes nothing, does not raise, and is logged" do
+ detail lendingRates: "not-an-array"
+
+ assert_difference -> { DebugLogEntry.count }, 1 do
+ assert_nothing_raised { process }
+ end
+
+ assert_empty schedule
+ end
+
+ # Row 15: the model refuses 150%, and the sync survives it.
+ test "a rate the model refuses is logged rather than raised" do
+ detail lendingRate: "1.5"
+
+ assert_difference -> { DebugLogEntry.count }, 1 do
+ assert_nothing_raised { process }
+ end
+
+ assert_empty schedule, "a rate outside the valid range was recorded"
+ end
+
+ # The boundary of row 15: 100% is the form's own ceiling and is kept; a
+ # negative rate is as meaningless as 150%.
+ test "a rate at the ceiling is recorded and a negative one is not" do
+ detail lendingRate: "1.0"
+ process
+ assert_equal({ "2026-09-21" => BigDecimal(100) }, rates)
+
+ @loan.update_columns(variable_rate_schedule: {})
+ detail lendingRate: "-0.01"
+ assert_difference -> { DebugLogEntry.count }, 1 do
+ process
+ end
+ assert_empty schedule
+ end
+
+ # Row 9: the detected row reaches the engine, for a cut as well as a rise.
+ test "a detected cut re-amortises from the detection date" do
+ detail lendingRate: "0.0525"
+
+ process
+
+ events = Loan::RateResolver.for(@loan.reload)
+ .re_amortisation_events(Date.new(2026, 1, 1), Date.new(2027, 1, 1))
+
+ assert_includes events.map { |event| event[:date] }, Date.new(2026, 9, 21),
+ "the detected change did not reach the rate resolver, so nothing re-amortises"
+ end
+
+ private
+ # Stamped as fetched on the sync's own date, which is what the importer
+ # does on a successful refresh. `fetched_at:` lets a test make the snapshot
+ # stale on purpose.
+ # `in_time_zone`, never `Date#to_time`. `to_time` builds midnight in the
+ # SYSTEM zone, which the database stores as UTC and reads back shifted: on
+ # a machine at UTC+10, midnight on the 21st comes back as 14:00 on the
+ # 20th, `details_fetched_this_sync?` compares the 20th against an `as_of`
+ # of the 21st, and every test that expects a write fails -- locally only,
+ # while passing on a UTC CI runner.
+ 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.transform_keys(&:to_s)
+ ),
+ account_details_fetched_at: fetched_at
+ )
+ end
+
+ def process
+ RedbarkAccount::LoanDetailsProcessor.new(@redbark_account, as_of: @as_of).process
+ end
+
+ def schedule
+ (@loan.reload.variable_rate_schedule || {}).stringify_keys
+ end
+
+ # Assert the VALUE rather than the representation the processor passed in.
+ def rates
+ schedule.transform_values { |rate| BigDecimal(rate.to_s) }
+ end
+end
diff --git a/test/models/redbark_item/importer_test.rb b/test/models/redbark_item/importer_test.rb
index de52b9539e..48f57eea02 100644
--- a/test/models/redbark_item/importer_test.rb
+++ b/test/models/redbark_item/importer_test.rb
@@ -6,6 +6,124 @@ class RedbarkItem::ImporterTest < ActiveSupport::TestCase
@importer = RedbarkItem::Importer.new(@redbark_item, redbark_provider: nil)
end
+ # Row 7: account details are the one thing in the sync a loan's rate
+ # depends on, and the one thing a user can live without. A failure there must
+ # not cost them balances or transactions.
+ test "a failing account details fetch leaves the payload alone and does not raise" do
+ redbark_account = redbark_accounts(:savings_account)
+ family = redbark_account.redbark_item.family
+ account = family.accounts.create!(
+ name: "Mortgage", balance: 400_000, currency: "AUD",
+ accountable: Loan.new(rate_type: "variable", interest_rate: 6.25)
+ )
+ redbark_account.ensure_account_provider!(account)
+ redbark_account.update!(raw_account_details_payload: { "lendingRate" => "0.0625" })
+
+ provider = mock
+ provider.stubs(:list_connections).returns([])
+ provider.stubs(:get_account_details).raises(Provider::Redbark::Error.new("boom", :server_error))
+ importer = RedbarkItem::Importer.new(redbark_account.redbark_item, redbark_provider: provider)
+
+ assert_nothing_raised do
+ importer.send(:import_loan_account_details, [ redbark_account.reload ])
+ end
+
+ assert_equal({ "lendingRate" => "0.0625" }, redbark_account.reload.raw_account_details_payload,
+ "a failed fetch overwrote the details the last good sync stored")
+ end
+
+ # The stamp is the sync's clock, injected, not the importer's own reading of
+ # it. Both phases of a sync have to agree on which day the snapshot belongs
+ # to; see RedbarkItem::SyncerTest for why they must not read the clock twice.
+ test "the injected clock stamps the snapshot, not the wall clock" do
+ redbark_account = redbark_accounts(:savings_account)
+ family = redbark_account.redbark_item.family
+ account = family.accounts.create!(
+ name: "Mortgage", balance: 400_000, currency: "AUD",
+ accountable: Loan.new(rate_type: "variable", interest_rate: 6.25)
+ )
+ redbark_account.ensure_account_provider!(account)
+
+ injected = Time.utc(2026, 9, 21, 23, 59, 30)
+ provider = mock
+ provider.stubs(:list_connections).returns([])
+ provider.stubs(:get_account_details).returns([
+ { accountId: redbark_account.redbark_account_id, lendingRate: "0.0675" }
+ ])
+ importer = RedbarkItem::Importer.new(
+ redbark_account.redbark_item, redbark_provider: provider, fetched_at: injected
+ )
+
+ travel_to Time.utc(2026, 9, 22, 0, 0, 30) do
+ importer.send(:import_loan_account_details, [ redbark_account.reload ])
+ end
+
+ assert_equal injected, redbark_account.reload.account_details_fetched_at.utc,
+ "the importer stamped its own reading of the clock instead of the sync's"
+ end
+
+ # The batch is rejected whole when one id is stale or of the wrong category,
+ # so one bad account must not cost every other loan its rate. Mirrors
+ # fetch_balances_with_fallback.
+ #
+ # Two DISTINCT accounts, because the fallback only engages for a batch of
+ # more than one: with a single id there is nothing to demote to.
+ test "a rejected batch falls back to one call per account" do
+ first = redbark_accounts(:savings_account)
+ item = first.redbark_item
+ family = item.family
+ second = item.redbark_accounts.create!(
+ redbark_account_id: "rb_acc_loan_2", name: "Second loan", currency: "AUD"
+ )
+
+ [ first, second ].each_with_index do |redbark_account, index|
+ account = family.accounts.create!(
+ name: "Mortgage #{index}", balance: 400_000, currency: "AUD",
+ accountable: Loan.new(rate_type: "variable", interest_rate: 6.25)
+ )
+ redbark_account.ensure_account_provider!(account)
+ end
+
+ provider = mock
+ provider.stubs(:list_connections).returns([])
+ provider.expects(:get_account_details)
+ .with(account_ids: [ first.redbark_account_id, second.redbark_account_id ])
+ .raises(Provider::Redbark::Error.new("stale id", :not_found))
+ provider.expects(:get_account_details)
+ .with(account_ids: [ first.redbark_account_id ])
+ .returns([ { accountId: first.redbark_account_id, lendingRate: "0.0675" } ])
+ provider.expects(:get_account_details)
+ .with(account_ids: [ second.redbark_account_id ])
+ .returns([])
+
+ importer = RedbarkItem::Importer.new(item, redbark_provider: provider)
+ importer.send(:import_loan_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"
+ assert_not_nil first.account_details_fetched_at, "a stored refresh was not stamped"
+ assert_nil second.reload.raw_account_details_payload,
+ "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
+ redbark_account = redbark_accounts(:savings_account)
+ family = redbark_account.redbark_item.family
+ account = family.accounts.create!(
+ name: "Everyday", balance: 100, currency: "AUD", accountable: Depository.new
+ )
+ redbark_account.ensure_account_provider!(account)
+
+ provider = mock
+ provider.stubs(:list_connections).returns([])
+ provider.expects(:get_account_details).never
+ importer = RedbarkItem::Importer.new(redbark_account.redbark_item, redbark_provider: provider)
+
+ importer.send(:import_loan_account_details, [ redbark_account.reload ])
+ end
+
test "merge_transactions keeps posted rows and refreshes by id" do
existing = [ { "id" => "t1", "status" => "posted", "date" => "2026-07-01", "amount" => "-10.00" } ]
fresh = [ { "id" => "t1", "status" => "posted", "date" => "2026-07-01", "amount" => "-12.00" } ]
diff --git a/test/models/redbark_item/syncer_test.rb b/test/models/redbark_item/syncer_test.rb
new file mode 100644
index 0000000000..46e73d303c
--- /dev/null
+++ b/test/models/redbark_item/syncer_test.rb
@@ -0,0 +1,77 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class RedbarkItem::SyncerTest < ActiveSupport::TestCase
+ setup do
+ @redbark_item = redbark_items(:one)
+ @redbark_account = redbark_accounts(:savings_account)
+ @family = @redbark_item.family
+
+ account = @family.accounts.create!(
+ name: "Mortgage", balance: 400_000, currency: "AUD",
+ accountable: Loan.new(rate_type: "variable", interest_rate: 6.25)
+ )
+ @redbark_account.ensure_account_provider!(account)
+
+ @syncer = RedbarkItem::Syncer.new(@redbark_item)
+ end
+
+ # A sync reads the bank in one phase and acts on what it read in the next.
+ # RedbarkAccount::LoanDetailsProcessor decides whether a stored snapshot
+ # belongs to the sync now running by comparing the stamp the import wrote
+ # against the date the processing was given. If those two come from separate
+ # readings of the clock, a sync that fetches at 23:59 and processes at 00:00
+ # discards the snapshot it has just stored, and the rate change in it is lost
+ # until the bank happens to move the rate again.
+ #
+ # THE SYNC IS MADE TO CROSS MIDNIGHT, and that is the whole design of the
+ # test. Comparing the two values alone proves nothing: two separate readings
+ # of the clock return the same date on all but one run in 86,400, so a test
+ # that merely compared them would pass against the very defect it names --
+ # which is what the first version of this test did. The
+ # clock is moved past midnight while the import is in flight, so a second
+ # reading taken afterwards can only disagree with the first.
+ test "the account details stamp and the processing date come from one clock" do
+ stamped = nil
+ dated = nil
+ before_midnight = Time.zone.local(2026, 9, 21, 23, 59, 59)
+
+ travel_to before_midnight do
+ @redbark_item.expects(:import_latest_redbark_data).with { |**kwargs|
+ stamped = kwargs[:fetched_at]
+ # The fetch takes two seconds and the day turns while it runs.
+ travel_to Time.zone.local(2026, 9, 22, 0, 0, 1)
+ true
+ }.returns({})
+
+ @redbark_item.expects(:process_accounts).with { |**kwargs|
+ dated = kwargs[:as_of]
+ true
+ }.returns([])
+
+ @syncer.perform_sync(mock_sync)
+ end
+
+ assert_kind_of Date, dated, "the processing phase was not given a date at all"
+ assert_not_nil stamped, "the import phase was not given a clock to stamp with"
+ assert_equal Date.new(2026, 9, 21), stamped.to_date,
+ "the stamp was not taken before midnight, so the test is not exercising the crossing"
+ assert_equal stamped.to_date, dated,
+ "the import stamped one date and the processing dated its findings by another"
+ end
+
+ private
+
+ def mock_sync
+ sync = mock("sync")
+ sync.stubs(:respond_to?).with(:status_text).returns(true)
+ sync.stubs(:respond_to?).with(:sync_stats).returns(true)
+ sync.stubs(:sync_stats).returns({})
+ sync.stubs(:created_at).returns(Time.current)
+ sync.stubs(:window_start_date).returns(nil)
+ sync.stubs(:window_end_date).returns(nil)
+ sync.stubs(:update!)
+ sync
+ end
+end