Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Date a Plaid variable rate change instead of moving the base rate (#4395)

jaysbeekay83195fe7e38d
diff --git a/app/models/family.rb b/app/models/family.rb
index 5ecd655dbe..ff2ddec28b 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -395,6 +395,15 @@ class Family < ApplicationRecord
AccountShare.insert_all(records, unique_by: %i[account_id user_id]) if records.any?
end
+ # The calendar date `time` falls on where the family lives. A background job
+ # runs in the app's zone (UTC unless configured), so a sync that dates what it
+ # finds by `Date.current` can land a day off the user's calendar. A blank or
+ # unknown zone falls back to the app's, as Localize#resolved_timezone does.
+ def local_date(time = Time.current)
+ zone = timezone.present? ? ActiveSupport::TimeZone[timezone] : nil
+ time.in_time_zone(zone || Time.zone).to_date
+ end
+
def uses_custom_month_start?
month_start_day != 1
end
diff --git a/app/models/loan.rb b/app/models/loan.rb
index 179a9c58a2..2e2cfca532 100644
--- a/app/models/loan.rb
+++ b/app/models/loan.rb
@@ -149,6 +149,49 @@ class Loan < ApplicationRecord
RateResolver.for(self).accrual_rate_for(as_of)
end
+ # What a provider should write when it reports this variable loan's rate on
+ # `as_of`, or nil when there is nothing to write. Writes nothing itself, so
+ # the provider's own writer keeps locks, provenance and refusal handling.
+ #
+ # - A first sighting (no base rate yet) sets the base rate: a first reading
+ # is not evidence that the rate moved on any particular day.
+ # - A rate equal to the one in force on `as_of` is not a change. A row
+ # already dated `as_of` is the rate in force on `as_of`, so this also
+ # covers a second sync on the same day.
+ # - Otherwise the change is a row dated `as_of`. The base rate stays, since
+ # replacing it would re-price every period before the change.
+ # - A loan that is not variable gets nil; what a fixed loan does with a
+ # reported rate is the caller's decision.
+ #
+ # Rounded to three places, the precision of `interest_rate`, so a reading a
+ # hair off the stored rate is not taken for a change on every sync.
+ #
+ # A rate outside 0..MAX_INTEREST_RATE gets nil. The form rejects one, and
+ # nothing checks a schedule written any other way, so a provider reporting
+ # -1% or 150% has sent something other than a rate. So has one that is not
+ # a number at all, which gets nil too rather than raising out of the sync.
+ # The bound is checked before rounding, which would otherwise carry -0.0004
+ # or 100.0004 onto 0 or 100.
+ def variable_rate_update_for(reported_rate, as_of:)
+ return nil if reported_rate.nil? || !variable_rate_type?
+
+ rate = begin
+ BigDecimal(reported_rate.to_s)
+ rescue ArgumentError, TypeError, FloatDomainError
+ nil
+ end
+ return nil unless rate&.finite? && rate.between?(0, MAX_INTEREST_RATE)
+
+ rate = rate.round(3)
+ return { interest_rate: rate } if interest_rate.blank?
+
+ in_force = current_variable_rate(as_of)
+ return nil if in_force.present? && BigDecimal(in_force.to_s) == rate
+
+ schedule = (variable_rate_schedule || {}).stringify_keys
+ { variable_rate_schedule: schedule.merge(as_of.to_date.iso8601 => rate.to_s("F")) }
+ end
+
# Rows the form submitted that could not be parsed. Kept so the save can be
# rejected and the form re-rendered with what the user actually typed --
# dropping them silently loses a typo'd row between submit and redisplay,
diff --git a/app/models/plaid_account/importer.rb b/app/models/plaid_account/importer.rb
index f12c10bdd0..81b5c82ad4 100644
--- a/app/models/plaid_account/importer.rb
+++ b/app/models/plaid_account/importer.rb
@@ -8,7 +8,11 @@ class PlaidAccount::Importer
import_account_info
import_transactions if account_snapshot.transactions_data.present?
import_investments if account_snapshot.investments_data.present?
- import_liabilities if account_snapshot.liabilities_data.present?
+ if account_snapshot.liabilities_data.present?
+ import_liabilities
+ elsif plaid_account.raw_liabilities_payload.present?
+ clear_liabilities
+ end
end
private
@@ -29,4 +33,11 @@ class PlaidAccount::Importer
def import_liabilities
plaid_account.upsert_plaid_liabilities_snapshot!(account_snapshot.liabilities_data)
end
+
+ # This sync fetched no liabilities, so a payload still stored is an earlier
+ # sync's. Processed again, a variable loan would record its rate as a
+ # change dated to this sync.
+ def clear_liabilities
+ plaid_account.upsert_plaid_liabilities_snapshot!({})
+ end
end
diff --git a/app/models/plaid_account/liabilities/loan_term_writer.rb b/app/models/plaid_account/liabilities/loan_term_writer.rb
new file mode 100644
index 0000000000..6ab9f3c2cd
--- /dev/null
+++ b/app/models/plaid_account/liabilities/loan_term_writer.rb
@@ -0,0 +1,122 @@
+# The one write path for a loan's terms from a Plaid payload, shared by the
+# mortgage and student-loan processors.
+#
+# Both used to call `loan.update!` straight from the payload, which:
+#
+# - overwrote a value the user corrected on the loan form, which
+# `Account#lock_saved_attributes!` had locked;
+# - recorded no provenance, so nothing said the value was Plaid's;
+# - blanked a stored value whenever the payload omitted the field, because
+# the omission arrived as nil.
+#
+# `Enrichable#enrich_attributes` answers the first two, as it already does for
+# `RedbarkAccount::LoanDetailsProcessor#write`; `compact` answers the third.
+#
+# A variable loan's new rate is a row in `variable_rate_schedule` dated to the
+# sync's `as_of`, which each including processor supplies, rather than a new
+# base rate (Loan#variable_rate_update_for).
+module PlaidAccount::Liabilities::LoanTermWriter
+ extend ActiveSupport::Concern
+
+ private
+ # Only nil means "the payload did not say". A rate of exactly 0 is a real
+ # figure for an interest-free loan and is written like any other.
+ def write_loan_terms(**attrs)
+ loan = account&.loan
+ return if loan.nil?
+
+ present = attrs.compact
+ return if present.empty?
+
+ terms = present.except(:interest_rate)
+ rate = present[:interest_rate]
+
+ # Two saves: the other terms first, so a payload that reclassifies the
+ # loan is applied before its rate is judged, then the rate. They land
+ # together or not at all, as the single save did.
+ #
+ # Enrichable logs the DataEnrichment before it saves, and a refused save
+ # does not roll that row back. This transaction does, so provenance never
+ # says Plaid supplied a value the loan rejected. `requires_new`, so the
+ # rollback holds even when a caller has a transaction open.
+ refusal = nil
+ loan.transaction(requires_new: true) do
+ refusal = enrich(loan, terms) || (rate.nil? ? nil : enrich(loan, rate_update(loan, rate)))
+ raise ActiveRecord::Rollback if refusal
+ end
+ return if refusal.nil?
+
+ # A refusal leaves the rejected values assigned and the errors populated
+ # on the in-memory loan, and a rolled-back first save leaves its values
+ # there too. Left in place, the next write in the same sync is refused
+ # for them, and a later no-op write reports them again.
+ loan.reload
+ loan.errors.clear
+
+ # Logged after the rollback so the entry is not rolled back with it.
+ report_refusal(loan, present.keys.map(&:to_s), refusal)
+ end
+
+ # A fixed loan's rate is its base rate, as before. A variable loan's is
+ # decided by the loan: a first sighting sets the base rate, an unchanged
+ # rate writes nothing, a change is a row dated `as_of`.
+ #
+ # Not from an import that stopped for a fresh login: PlaidItem::Importer
+ # swallows ITEM_LOGIN_REQUIRED and marks the item, and the sync still
+ # processes, so this payload is the previous sync's. Its rate is not a
+ # change the bank reported on `as_of`, and dating it would route around a
+ # base rate the user has since corrected and locked. The status means
+ # "this import" because PlaidItem::Importer#import puts it back to good
+ # after a fetch that succeeds.
+ #
+ # The guard sits after the fixed branch on purpose: a stale fixed rate is
+ # the value the last sync already wrote, and a user's correction to it is
+ # locked, so rewriting it changes nothing. Only the variable path would
+ # turn the stale rate into a new dated row.
+ def rate_update(loan, rate)
+ return { interest_rate: rate } unless loan.variable_rate_type?
+ return nil if plaid_account.plaid_item.requires_update?
+
+ loan.variable_rate_update_for(rate, as_of: as_of)
+ end
+
+ # Writes through Enrichable and returns nil, or the model's error messages
+ # when it refused them. `false` from Enrichable alone is not a refusal: it
+ # also means every attribute was locked or unchanged.
+ def enrich(loan, attrs)
+ return nil if attrs.blank?
+
+ loan.enrich_attributes(attrs, source: "plaid")
+ loan.errors.empty? ? nil : loan.errors.full_messages
+ end
+
+ # `enrich_attributes` saves with `save`, so a refusal returns false where
+ # `update!` raised into PlaidAccount::Processor#process_liabilities's
+ # rescue, which sent it to Sentry. Both are kept: the debug log for support,
+ # filtered by the connection, and Sentry so a refusal that recurs every
+ # sync still shows in error monitoring. The errors are passed in because
+ # the loan has been reloaded by the time this runs.
+ def report_refusal(loan, attributes, errors)
+ message = "Plaid loan terms refused by the model"
+
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "warn",
+ message: message,
+ source: self.class.name,
+ provider_key: "plaid",
+ account: account,
+ account_provider: plaid_account.account_provider,
+ metadata: {
+ plaid_account_id: plaid_account.id,
+ attributes: attributes,
+ errors: errors
+ }
+ )
+
+ Sentry.capture_message(message, level: :warning) do |scope|
+ scope.set_tags(plaid_account_id: plaid_account.id)
+ scope.set_context("plaid_loan_terms", { loan_id: loan.id, attributes: attributes, errors: errors })
+ end
+ end
+end
diff --git a/app/models/plaid_account/liabilities/mortgage_processor.rb b/app/models/plaid_account/liabilities/mortgage_processor.rb
index d5744c9a72..6a267edb98 100644
--- a/app/models/plaid_account/liabilities/mortgage_processor.rb
+++ b/app/models/plaid_account/liabilities/mortgage_processor.rb
@@ -1,19 +1,24 @@
class PlaidAccount::Liabilities::MortgageProcessor
- def initialize(plaid_account)
+ include PlaidAccount::Liabilities::LoanTermWriter
+
+ # `as_of` is the sync's date: a variable rate change Plaid reports is dated
+ # to it.
+ def initialize(plaid_account, as_of: Date.current)
@plaid_account = plaid_account
+ @as_of = as_of
end
def process
return unless mortgage_data.present?
- account.loan.update!(
+ write_loan_terms(
rate_type: mortgage_data.dig("interest_rate", "type"),
interest_rate: mortgage_data.dig("interest_rate", "percentage")
)
end
private
- attr_reader :plaid_account
+ attr_reader :plaid_account, :as_of
def account
plaid_account.current_account
diff --git a/app/models/plaid_account/liabilities/student_loan_processor.rb b/app/models/plaid_account/liabilities/student_loan_processor.rb
index 5ecbf9a969..6cd594c94d 100644
--- a/app/models/plaid_account/liabilities/student_loan_processor.rb
+++ b/app/models/plaid_account/liabilities/student_loan_processor.rb
@@ -1,12 +1,17 @@
class PlaidAccount::Liabilities::StudentLoanProcessor
- def initialize(plaid_account)
+ include PlaidAccount::Liabilities::LoanTermWriter
+
+ # `as_of` is the sync's date: a variable rate change Plaid reports is dated
+ # to it.
+ def initialize(plaid_account, as_of: Date.current)
@plaid_account = plaid_account
+ @as_of = as_of
end
def process
return unless student_loan_data.present?
- account.loan.update!(
+ write_loan_terms(
rate_type: "fixed",
interest_rate: student_loan_data["interest_rate_percentage"],
initial_balance: student_loan_data["origination_principal_amount"],
@@ -16,7 +21,7 @@ class PlaidAccount::Liabilities::StudentLoanProcessor
end
private
- attr_reader :plaid_account
+ attr_reader :plaid_account, :as_of
def account
plaid_account.current_account
diff --git a/app/models/plaid_account/processor.rb b/app/models/plaid_account/processor.rb
index 9871aeedf6..b17dccd9c0 100644
--- a/app/models/plaid_account/processor.rb
+++ b/app/models/plaid_account/processor.rb
@@ -3,10 +3,13 @@ class PlaidAccount::Processor
BalanceError = Class.new(StandardError)
- attr_reader :plaid_account
+ attr_reader :plaid_account, :as_of
- def initialize(plaid_account)
+ # `as_of` is the sync's date. Only the loan liability processors read it, to
+ # date a variable rate change.
+ def initialize(plaid_account, as_of: Date.current)
@plaid_account = plaid_account
+ @as_of = as_of
end
# Each step represents a different Plaid API endpoint / "product"
@@ -161,9 +164,9 @@ class PlaidAccount::Processor
if type == "credit"
PlaidAccount::Liabilities::CreditProcessor.new(plaid_account).process
elsif type == "loan" && subtype == "mortgage"
- PlaidAccount::Liabilities::MortgageProcessor.new(plaid_account).process
+ PlaidAccount::Liabilities::MortgageProcessor.new(plaid_account, as_of: as_of).process
elsif type == "loan" && subtype == "student"
- PlaidAccount::Liabilities::StudentLoanProcessor.new(plaid_account).process
+ PlaidAccount::Liabilities::StudentLoanProcessor.new(plaid_account, as_of: as_of).process
end
rescue => e
report_exception(e)
diff --git a/app/models/plaid_item.rb b/app/models/plaid_item.rb
index b2ffdba184..b719949f0d 100644
--- a/app/models/plaid_item.rb
+++ b/app/models/plaid_item.rb
@@ -118,9 +118,12 @@ class PlaidItem < ApplicationRecord
# Reads the fetched data and updates internal domain objects
# Generally, this should only be called within a "sync", but can be called
# manually to "re-sync" the already fetched data
- def process_accounts
+ #
+ # `as_of` is captured once and passed down, so every account in one sync
+ # dates a rate change the same way, as RedbarkItem#process_accounts does.
+ def process_accounts(as_of: Date.current)
plaid_accounts.each do |plaid_account|
- PlaidAccount::Processor.new(plaid_account).process
+ PlaidAccount::Processor.new(plaid_account, as_of: as_of).process
end
end
diff --git a/app/models/plaid_item/importer.rb b/app/models/plaid_item/importer.rb
index 8bcbf43e97..defca74321 100644
--- a/app/models/plaid_item/importer.rb
+++ b/app/models/plaid_item/importer.rb
@@ -36,6 +36,18 @@ class PlaidItem::Importer
plaid_item.upsert_plaid_institution_snapshot!(institution_data)
end
+ # Every stored account is processed after an import, but only the ones
+ # Plaid returned were imported. A liabilities payload left on any other is
+ # an earlier sync's, so it is cleared as PlaidAccount::Importer clears its
+ # own, rather than processed again as if fresh. The payload is encrypted,
+ # so its presence is read in Ruby.
+ def clear_liabilities_of_omitted_accounts(snapshot)
+ returned = snapshot.accounts.map(&:account_id)
+ plaid_item.plaid_accounts.where.not(plaid_id: returned).find_each do |plaid_account|
+ plaid_account.upsert_plaid_liabilities_snapshot!({}) if plaid_account.raw_liabilities_payload.present?
+ end
+ end
+
def fetch_and_import_accounts_data
snapshot = PlaidItem::AccountsSnapshot.new(plaid_item, plaid_provider: plaid_provider)
@@ -51,6 +63,8 @@ class PlaidItem::Importer
).import
end
+ clear_liabilities_of_omitted_accounts(snapshot)
+
# Once we know all data has been imported, save the cursor to avoid re-fetching the same data next time
plaid_item.update!(next_cursor: snapshot.transactions_cursor)
end
diff --git a/app/models/plaid_item/syncer.rb b/app/models/plaid_item/syncer.rb
index 1f90f68c6d..76d765d9c5 100644
--- a/app/models/plaid_item/syncer.rb
+++ b/app/models/plaid_item/syncer.rb
@@ -8,6 +8,11 @@ class PlaidItem::Syncer
end
def perform_sync(sync)
+ # The one "today" for this sync, handed to every account's processing. It
+ # is the family's date, not the job's: a sync at 06:00 in Sydney is still
+ # the previous day in UTC.
+ as_of = plaid_item.family.local_date
+
# Phase 1: Import data from Plaid API
sync.update!(status_text: "Importing accounts from Plaid...") if sync.respond_to?(:status_text)
plaid_item.import_latest_plaid_data
@@ -17,7 +22,7 @@ class PlaidItem::Syncer
# is what creates Account and AccountProvider records for new PlaidAccounts.
sync.update!(status_text: "Processing accounts...") if sync.respond_to?(:status_text)
mark_import_started(sync)
- plaid_item.process_accounts
+ plaid_item.process_accounts(as_of: as_of)
# Phase 3: Collect setup statistics (now that accounts have been processed)
sync.update!(status_text: "Checking account configuration...") if sync.respond_to?(:status_text)
diff --git a/app/models/redbark_account/loan_details_processor.rb b/app/models/redbark_account/loan_details_processor.rb
index 851b7c8a12..68c884abfa 100644
--- a/app/models/redbark_account/loan_details_processor.rb
+++ b/app/models/redbark_account/loan_details_processor.rb
@@ -52,7 +52,9 @@ class RedbarkAccount::LoanDetailsProcessor
fetched_at = redbark_account.account_details_fetched_at
return false if fetched_at.blank?
- fetched_at.to_date == as_of.to_date
+ # In the family's zone, as the syncer derives `as_of`; the stamp itself
+ # reads back in the app's zone.
+ redbark_account.redbark_item.family.local_date(fetched_at) == as_of.to_date
end
def account
@@ -115,11 +117,12 @@ class RedbarkAccount::LoanDetailsProcessor
# 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)
+ rate = decimal * 100
# 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)
+ # sent something other than a rate. Checked before rounding, which would
+ # otherwise carry -0.0004% or 100.0004% onto the bound.
+ return rate.round(3) 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
@@ -146,36 +149,11 @@ class RedbarkAccount::LoanDetailsProcessor
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) })
+ # First sighting, unchanged rate and dated change are the loan's rules,
+ # shared with Plaid. A first sighting that is locked or refused leaves
+ # the rate blank, so the next sync is a first sighting again rather than
+ # a change dated on a day nothing moved.
+ write(loan.variable_rate_update_for(reported_rate, as_of: as_of))
end
# `rate_type` is blank on a loan nobody has classified. A bank calling its
diff --git a/app/models/redbark_item/syncer.rb b/app/models/redbark_item/syncer.rb
index 1f9997d69b..27ebbec079 100644
--- a/app/models/redbark_item/syncer.rb
+++ b/app/models/redbark_item/syncer.rb
@@ -33,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(as_of: synced_at.to_date)
+ redbark_item.process_accounts(as_of: redbark_item.family.local_date(synced_at))
# 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/test/models/family_test.rb b/test/models/family_test.rb
index 26cfff8105..8f41cd6730 100644
--- a/test/models/family_test.rb
+++ b/test/models/family_test.rb
@@ -8,6 +8,28 @@ class FamilyTest < ActiveSupport::TestCase
@syncable = families(:dylan_family)
end
+ test "local_date is the date in the family's zone" do
+ family = families(:dylan_family)
+ evening_utc = Time.utc(2026, 1, 15, 19, 0, 0)
+
+ family.update!(timezone: "Australia/Sydney")
+ assert_equal Date.new(2026, 1, 16), family.local_date(evening_utc)
+
+ family.update!(timezone: "America/New_York")
+ assert_equal Date.new(2026, 1, 15), family.local_date(Time.utc(2026, 1, 16, 3, 0, 0))
+ end
+
+ test "local_date falls back to the app's zone for a blank or unknown zone" do
+ family = families(:dylan_family)
+ evening_utc = Time.utc(2026, 1, 15, 19, 0, 0)
+
+ family.update_column(:timezone, nil)
+ assert_equal evening_utc.in_time_zone(Time.zone).to_date, family.local_date(evening_utc)
+
+ family.update_column(:timezone, "Mars/Olympus_Mons")
+ assert_equal evening_utc.in_time_zone(Time.zone).to_date, family.local_date(evening_utc)
+ end
+
test "investment_contributions_category creates category when missing" do
family = families(:dylan_family)
family.categories.where(name: Category.investment_contributions_name).destroy_all
diff --git a/test/models/loan_test.rb b/test/models/loan_test.rb
index 5beddd1bd1..60cb636753 100644
--- a/test/models/loan_test.rb
+++ b/test/models/loan_test.rb
@@ -228,6 +228,125 @@ class LoanTest < ActiveSupport::TestCase
assert_equal 80_000, account.loan.reload.original_balance.amount
end
+ # The dated-rate rule every provider that reports a variable rate applies.
+ # The loan answers what should be written; the provider's writer writes it.
+ test "variable_rate_update_for sets the base rate on a first sighting" do
+ loan = Loan.new(rate_type: "variable", interest_rate: nil)
+
+ assert_equal({ interest_rate: BigDecimal("5.2") },
+ loan.variable_rate_update_for(5.2, as_of: Date.new(2026, 1, 15)))
+ end
+
+ test "variable_rate_update_for dates a moved rate to as_of, not today" do
+ loan = Loan.new(rate_type: "variable", interest_rate: 4.5)
+
+ update = loan.variable_rate_update_for(5.2, as_of: Date.new(2026, 1, 15))
+
+ assert_equal({ "2026-01-15" => "5.2" }, update[:variable_rate_schedule])
+ assert_not update.key?(:interest_rate), "the base rate must not move"
+ end
+
+ test "variable_rate_update_for keeps the rows already on the schedule" do
+ loan = Loan.new(rate_type: "variable", interest_rate: 4.5,
+ variable_rate_schedule: { "2025-06-01" => "4.8" })
+
+ update = loan.variable_rate_update_for(5.2, as_of: Date.new(2026, 1, 15))
+
+ assert_equal({ "2025-06-01" => "4.8", "2026-01-15" => "5.2" }, update[:variable_rate_schedule])
+ end
+
+ test "variable_rate_update_for records nothing when the rate in force is unchanged" do
+ loan = Loan.new(rate_type: "variable", interest_rate: 4.5,
+ variable_rate_schedule: { "2025-06-01" => "5.125" })
+
+ # A four-place reading of the three-place stored rate is not a change.
+ assert_nil loan.variable_rate_update_for(BigDecimal("5.1249"), as_of: Date.new(2026, 1, 15))
+ end
+
+ test "variable_rate_update_for records nothing when the as_of row already holds the rate" do
+ loan = Loan.new(rate_type: "variable", interest_rate: 4.5,
+ variable_rate_schedule: { "2026-01-15" => "5.2" })
+
+ assert_nil loan.variable_rate_update_for(5.2, as_of: Date.new(2026, 1, 15))
+ end
+
+ # A provider's own word for a moving rate ("arm") is variable, as
+ # Loan#variable_rate_type? reads it.
+ test "variable_rate_update_for treats a provider's rate type as variable" do
+ loan = Loan.new(rate_type: "arm", interest_rate: 4.5)
+
+ assert_equal({ "2026-01-15" => "5.2" },
+ loan.variable_rate_update_for(5.2, as_of: Date.new(2026, 1, 15))[:variable_rate_schedule])
+ end
+
+ test "variable_rate_update_for leaves a fixed loan to its caller" do
+ loan = Loan.new(rate_type: "fixed", interest_rate: 4.5)
+
+ assert_nil loan.variable_rate_update_for(5.2, as_of: Date.new(2026, 1, 15))
+ end
+
+ # The form rejects a rate outside 0..MAX_INTEREST_RATE, and nothing in the
+ # model checks a schedule written any other way, so the rule every provider
+ # shares carries the same bound.
+ test "variable_rate_update_for records nothing for a rate outside the form's bounds" do
+ as_of = Date.new(2026, 1, 15)
+ moved = Loan.new(rate_type: "variable", interest_rate: 4.5)
+ first = Loan.new(rate_type: "variable", interest_rate: nil)
+
+ [ -0.001, Loan::MAX_INTEREST_RATE + 0.001, BigDecimal("Infinity"), BigDecimal("NaN") ].each do |rate|
+ assert_nil moved.variable_rate_update_for(rate, as_of: as_of), "#{rate} was dated as a change"
+ assert_nil first.variable_rate_update_for(rate, as_of: as_of), "#{rate} was set as the base rate"
+ end
+ end
+
+ # The bound is checked before the three-place rounding, which would
+ # otherwise carry a reading just outside it onto 0 or 100.
+ test "variable_rate_update_for checks the bound before rounding" do
+ as_of = Date.new(2026, 1, 15)
+ moved = Loan.new(rate_type: "variable", interest_rate: 4.5)
+ first = Loan.new(rate_type: "variable", interest_rate: nil)
+
+ [ BigDecimal("-0.0004"), BigDecimal("100.0004") ].each do |rate|
+ assert_nil moved.variable_rate_update_for(rate, as_of: as_of), "#{rate.to_s("F")} was dated as a change"
+ assert_nil first.variable_rate_update_for(rate, as_of: as_of), "#{rate.to_s("F")} was set as the base rate"
+ end
+ end
+
+ # A reading inside the bound that rounds onto it is still a rate.
+ test "variable_rate_update_for rounds an in-bound reading after checking it" do
+ as_of = Date.new(2026, 1, 15)
+
+ assert_equal({ "2026-01-15" => "100.0" },
+ Loan.new(rate_type: "variable", interest_rate: 4.5)
+ .variable_rate_update_for(BigDecimal("99.9996"), as_of: as_of)[:variable_rate_schedule])
+ assert_equal({ interest_rate: BigDecimal("100") },
+ Loan.new(rate_type: "variable", interest_rate: nil)
+ .variable_rate_update_for(BigDecimal("99.9996"), as_of: as_of))
+ end
+
+ # A provider's rate is external input. One that is not a number is ignored
+ # like one out of bounds, rather than raising and costing the sync the
+ # other terms it reported.
+ test "variable_rate_update_for records nothing for a rate that is not a number" do
+ as_of = Date.new(2026, 1, 15)
+ moved = Loan.new(rate_type: "variable", interest_rate: 4.5)
+ first = Loan.new(rate_type: "variable", interest_rate: nil)
+
+ [ "n/a", "", "5.2%", true ].each do |rate|
+ assert_nil moved.variable_rate_update_for(rate, as_of: as_of), "#{rate.inspect} was dated as a change"
+ assert_nil first.variable_rate_update_for(rate, as_of: as_of), "#{rate.inspect} was set as the base rate"
+ end
+ end
+
+ test "variable_rate_update_for accepts both ends of the form's bounds" do
+ as_of = Date.new(2026, 1, 15)
+ loan = Loan.new(rate_type: "variable", interest_rate: 4.5)
+
+ assert_equal({ "2026-01-15" => "0.0" }, loan.variable_rate_update_for(0, as_of: as_of)[:variable_rate_schedule])
+ assert_equal({ "2026-01-15" => "100.0" },
+ loan.variable_rate_update_for(Loan::MAX_INTEREST_RATE, as_of: as_of)[:variable_rate_schedule])
+ end
+
private
# A loan imported part way through its life: the principal it was written
# for is recorded, and the only valuation the account carries is the
diff --git a/test/models/plaid_account/importer_test.rb b/test/models/plaid_account/importer_test.rb
index 69fcf489d9..a84752fe41 100644
--- a/test/models/plaid_account/importer_test.rb
+++ b/test/models/plaid_account/importer_test.rb
@@ -43,4 +43,28 @@ class PlaidAccount::ImporterTest < ActiveSupport::TestCase
PlaidAccount::Importer.new(@plaid_account, account_snapshot: @mock_account_snapshot).import
end
+
+ # A sync that fetched no liabilities would otherwise process the payload a
+ # previous sync stored, and a variable loan would record that old rate as a
+ # change dated to this sync.
+ test "a sync without liabilities data clears the stored liabilities payload" do
+ @plaid_account.update!(raw_liabilities_payload: { "mortgage" => { "interest_rate" => { "percentage" => 4.5 } } })
+ snapshot = OpenStruct.new(account_data: nil, transactions_data: nil, investments_data: nil, liabilities_data: nil)
+ @plaid_account.stubs(:upsert_plaid_snapshot!)
+
+ PlaidAccount::Importer.new(@plaid_account, account_snapshot: snapshot).import
+
+ assert_equal({}, @plaid_account.reload.raw_liabilities_payload)
+ end
+
+ test "a sync without liabilities data leaves an account that never had them unwritten" do
+ @plaid_account.update_columns(raw_liabilities_payload: nil)
+ snapshot = OpenStruct.new(account_data: nil, transactions_data: nil, investments_data: nil, liabilities_data: nil)
+ @plaid_account.stubs(:upsert_plaid_snapshot!)
+ @plaid_account.expects(:upsert_plaid_liabilities_snapshot!).never
+
+ PlaidAccount::Importer.new(@plaid_account, account_snapshot: snapshot).import
+
+ assert_nil @plaid_account.reload.raw_liabilities_payload
+ end
end
diff --git a/test/models/plaid_account/liabilities/mortgage_processor_test.rb b/test/models/plaid_account/liabilities/mortgage_processor_test.rb
index 65e9e27c15..c7285a1a06 100644
--- a/test/models/plaid_account/liabilities/mortgage_processor_test.rb
+++ b/test/models/plaid_account/liabilities/mortgage_processor_test.rb
@@ -1,6 +1,9 @@
require "test_helper"
class PlaidAccount::Liabilities::MortgageProcessorTest < ActiveSupport::TestCase
+ # Rate changes are dated after it, so the loan accepts them.
+ ORIGINATED = Date.new(2020, 1, 1)
+
setup do
@plaid_account = plaid_accounts(:one)
@plaid_account.update!(
@@ -63,4 +66,365 @@ class PlaidAccount::Liabilities::MortgageProcessorTest < ActiveSupport::TestCase
assert_nil loan.rate_type
assert_nil loan.interest_rate
end
+
+ # A value the user corrected on the loan form is locked by
+ # Account#lock_saved_attributes!, and a sync must not overwrite it.
+ test "a locked interest rate is not overwritten by Plaid" do
+ loan = loan_with(interest_rate: 4.5)
+ loan.lock_attr!(:interest_rate)
+ payload(type: "fixed", percentage: 5.2)
+
+ process
+
+ assert_equal 4.5, loan.reload.interest_rate.to_f, "Plaid overwrote a rate the user had locked"
+ assert_equal "fixed", loan.rate_type, "the unlocked attribute beside it was not written"
+ end
+
+ test "a locked rate type is not overwritten by Plaid" do
+ loan = loan_with(rate_type: "variable", interest_rate: 4.5)
+ loan.lock_attr!(:rate_type)
+ payload(type: "fixed", percentage: 4.5)
+
+ process
+
+ assert_equal "variable", loan.reload.rate_type, "Plaid overwrote a rate type the user had locked"
+ end
+
+ test "an unlocked loan is updated and Plaid is recorded as the source" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "variable")
+ payload(type: "fixed", percentage: 5.2)
+
+ assert_difference -> { DataEnrichment.where(enrichable: loan).count }, 2 do
+ process
+ end
+
+ loan.reload
+ assert_equal 5.2, loan.interest_rate.to_f
+ assert_equal "fixed", loan.rate_type
+ assert_equal [ "plaid" ], DataEnrichment.where(enrichable: loan).pluck(:source).uniq
+ end
+
+ # An omitted field is not a value: sending nil blanked the stored rate.
+ test "a payload without a percentage leaves the stored rate alone" do
+ loan = loan_with(interest_rate: 4.5)
+ payload(type: "fixed")
+
+ process
+
+ assert_equal 4.5, loan.reload.interest_rate.to_f, "an omitted percentage blanked the stored rate"
+ assert_equal "fixed", loan.rate_type, "the field the payload did carry was not written"
+ end
+
+ # The other side of that boundary: zero is a real rate, not an absent one.
+ test "a rate of exactly zero is written" do
+ loan = loan_with(interest_rate: 4.5)
+ payload(type: "fixed", percentage: 0)
+
+ process
+
+ assert_equal 0.0, loan.reload.interest_rate.to_f, "an interest-free loan's zero was dropped as if absent"
+ end
+
+ test "the same payload twice records provenance once" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "variable")
+ payload(type: "fixed", percentage: 5.2)
+
+ assert_difference -> { DataEnrichment.where(enrichable: loan).count }, 2 do
+ process
+ end
+
+ assert_no_difference -> { DataEnrichment.where(enrichable: loan).count } do
+ process
+ end
+ end
+
+ # Enrichable saves with `save`, not `save!`, so a refusal returns false
+ # instead of raising into PlaidAccount::Processor's rescue. It must still be
+ # reported. Here the refusal is Loan's own rule: a loan turned variable
+ # cannot carry a rate change dated before its start date.
+ test "a value the model refuses is logged rather than raised" do
+ loan = loan_refusing_variable
+ payload(type: "arm", percentage: 5.2)
+
+ assert_difference -> { DebugLogEntry.where(provider_key: "plaid").count }, 1 do
+ assert_nothing_raised { process }
+ end
+
+ loan.reload
+ assert_equal "fixed", loan.rate_type, "a refused rate type was stored anyway"
+ assert_equal 4.5, loan.interest_rate.to_f, "a refused batch was partly stored"
+ end
+
+ # Support filters /settings/debug by connection, and DebugLogEntry does not
+ # derive the link from the account, so the row must carry it.
+ test "a refusal is logged against the Plaid connection" do
+ link = AccountProvider.create!(account: @plaid_account.current_account, provider: @plaid_account)
+ loan_refusing_variable
+ payload(type: "arm", percentage: 5.2)
+
+ process
+
+ entry = DebugLogEntry.where(provider_key: "plaid").order(:created_at).last
+ assert_equal link.id, entry.account_provider_id, "the refusal was logged without its connection"
+ end
+
+ # Before the write went through Enrichable, a refusal raised into
+ # PlaidAccount::Processor#process_liabilities's rescue and reached Sentry.
+ # A refusal that keeps recurring must stay visible in error monitoring.
+ test "a refusal is reported to Sentry" do
+ loan_refusing_variable
+ payload(type: "arm", percentage: 5.2)
+
+ Sentry.expects(:capture_message).with("Plaid loan terms refused by the model", level: :warning).once
+
+ process
+ end
+
+ # The other side: a write that changes nothing is not a refusal.
+ test "a locked or unchanged write is not reported to Sentry" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "fixed")
+ loan.lock_attr!(:interest_rate)
+ payload(type: "fixed", percentage: 5.2)
+
+ Sentry.expects(:capture_message).never
+
+ process
+ end
+
+ # A refused write must not attribute the rejected value to Plaid. Enrichable
+ # writes the DataEnrichment before it saves, and reuses the row an earlier
+ # accepted write made, so only the stored value shows this.
+ test "a refused value leaves the earlier provenance in place" do
+ loan = loan_refusing_variable(rate_type: nil)
+ writer = PlaidAccount::Liabilities::MortgageProcessor.new(@plaid_account.reload)
+
+ writer.send(:write_loan_terms, rate_type: "fixed")
+ enrichment = DataEnrichment.find_by!(enrichable: loan, attribute_name: "rate_type", source: "plaid")
+
+ writer.send(:write_loan_terms, rate_type: "arm")
+
+ assert_equal "fixed", enrichment.reload.value, "the refused value was recorded as Plaid's"
+ assert_equal "fixed", loan.reload.rate_type
+ end
+
+ # The rollback must hold when the caller already has a transaction open;
+ # a nested Rollback that merely joins it is swallowed and undoes nothing.
+ test "a refused value inside a caller's transaction leaves the earlier provenance in place" do
+ loan = loan_refusing_variable(rate_type: nil)
+ writer = PlaidAccount::Liabilities::MortgageProcessor.new(@plaid_account.reload)
+ writer.send(:write_loan_terms, rate_type: "fixed")
+ enrichment = DataEnrichment.find_by!(enrichable: loan, attribute_name: "rate_type", source: "plaid")
+
+ ActiveRecord::Base.transaction do
+ writer.send(:write_loan_terms, rate_type: "arm")
+ end
+
+ assert_equal "fixed", enrichment.reload.value, "the refused value was recorded as Plaid's"
+ end
+
+ # A refusal leaves the rejected value assigned on the processor's loan. The
+ # next write in the same sync would then be refused for it, losing a change
+ # it had every right to.
+ test "a refused value does not cost the next write its change" do
+ loan = loan_refusing_variable
+ writer = PlaidAccount::Liabilities::MortgageProcessor.new(@plaid_account.reload)
+
+ writer.send(:write_loan_terms, rate_type: "arm")
+ writer.send(:write_loan_terms, interest_rate: 5.2)
+
+ loan.reload
+ assert_equal 5.2, loan.interest_rate.to_f, "a valid change was refused because of an earlier rejected value"
+ assert_equal "fixed", loan.rate_type
+ end
+
+ # And the errors: Enrichable returns early without saving when every
+ # attribute is locked, so stale errors would be reported as a second refusal.
+ test "a refusal leaves no errors behind for a locked write to report" do
+ loan = loan_refusing_variable
+ loan.lock_attr!(:interest_rate)
+ writer = PlaidAccount::Liabilities::MortgageProcessor.new(@plaid_account.reload)
+
+ assert_difference -> { DebugLogEntry.where(provider_key: "plaid").count }, 1 do
+ writer.send(:write_loan_terms, rate_type: "arm")
+ writer.send(:write_loan_terms, interest_rate: 5.2)
+ end
+
+ assert_equal 4.5, loan.reload.interest_rate.to_f
+ end
+
+ # A variable loan's rate change is a dated row, not a new base rate:
+ # replacing the base rate re-prices every period before the change.
+ test "a variable mortgage's rate change is dated, not overwritten" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "variable", start_date: ORIGINATED)
+ payload(type: "variable", percentage: 5.2)
+
+ process_as_of(Date.new(2026, 1, 15))
+
+ loan.reload
+ assert_equal 4.5, loan.interest_rate.to_f, "the base rate was overwritten"
+ assert_equal({ "2026-01-15" => 5.2 }, rates(loan))
+ end
+
+ # PlaidItem::Importer#handle_plaid_error swallows ITEM_LOGIN_REQUIRED and
+ # the sync still processes, so the payload is the previous sync's. A rate
+ # from it is not a change the bank reported today, and dating it would
+ # route around a rate the user has since corrected and locked.
+ test "a rate from an import that needed a fresh login is not dated" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "variable", start_date: ORIGINATED)
+ loan.lock_attr!(:interest_rate)
+ payload(type: "variable", percentage: 5.2)
+ @plaid_account.plaid_item.update!(status: :requires_update)
+
+ process_as_of(Date.new(2026, 1, 15))
+
+ loan.reload
+ assert_equal({}, rates(loan), "a stale payload's rate was dated as a change")
+ assert_equal 4.5, loan.interest_rate.to_f
+ end
+
+ # The rate is ignored, as one out of bounds is, and the rate type from the
+ # same payload still lands instead of the whole write being lost.
+ test "a variable rate that is not a number is ignored and the rate type still lands" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "fixed", start_date: ORIGINATED)
+ payload(type: "variable", percentage: "n/a")
+
+ process_as_of(Date.new(2026, 1, 15))
+
+ loan.reload
+ assert_equal "variable", loan.rate_type
+ assert_equal 4.5, loan.interest_rate.to_f
+ assert_equal({}, rates(loan))
+ end
+
+ test "a rate change under Plaid's own rate type is dated too" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "arm", start_date: ORIGINATED)
+ payload(type: "arm", percentage: 5.2)
+
+ process_as_of(Date.new(2026, 1, 15))
+
+ loan.reload
+ assert_equal 4.5, loan.interest_rate.to_f, "the base rate was overwritten"
+ assert_equal({ "2026-01-15" => 5.2 }, rates(loan))
+ end
+
+ test "the dated row is keyed to the sync's date, not the clock" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "variable", start_date: ORIGINATED)
+ payload(type: "variable", percentage: 5.2)
+
+ travel_to Date.new(2026, 3, 1) do
+ process_as_of(Date.new(2026, 1, 15))
+ end
+
+ assert_equal [ "2026-01-15" ], rates(loan.reload).keys
+ end
+
+ test "the same variable rate on the next sync adds no second row" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "variable", start_date: ORIGINATED)
+ payload(type: "variable", percentage: 5.2)
+ process_as_of(Date.new(2026, 1, 15))
+
+ process_as_of(Date.new(2026, 1, 16))
+
+ assert_equal({ "2026-01-15" => 5.2 }, rates(loan.reload))
+ end
+
+ test "a payload that turns a fixed loan variable dates the rate change" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "fixed", start_date: ORIGINATED)
+ payload(type: "variable", percentage: 5.2)
+
+ process_as_of(Date.new(2026, 1, 15))
+
+ loan.reload
+ assert_equal "variable", loan.rate_type
+ assert_equal 4.5, loan.interest_rate.to_f
+ assert_equal({ "2026-01-15" => 5.2 }, rates(loan))
+ end
+
+ # The negative case: a fixed loan's rate is still the base rate.
+ test "a fixed mortgage's rate is still written as the base rate" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "fixed", start_date: ORIGINATED)
+ payload(type: "fixed", percentage: 5.2)
+
+ process_as_of(Date.new(2026, 1, 15))
+
+ loan.reload
+ assert_equal 5.2, loan.interest_rate.to_f
+ assert_empty rates(loan), "a fixed loan grew a schedule"
+ end
+
+ test "a locked schedule is not written" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "variable", start_date: ORIGINATED)
+ loan.lock_attr!(:variable_rate_schedule)
+ payload(type: "variable", percentage: 5.2)
+
+ process_as_of(Date.new(2026, 1, 15))
+
+ loan.reload
+ assert_empty rates(loan)
+ assert_equal 4.5, loan.interest_rate.to_f
+ end
+
+ # The variable path is two saves: the terms, then the rate judged against the
+ # loan they produce. They must land together, as the single save did, or a
+ # reclassification to variable commits without the rate that came with it.
+ # The rate row is refused here because it predates the loan's start date.
+ test "a move to variable whose rate row is refused changes nothing" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "fixed", start_date: Date.new(2026, 2, 1))
+ writer = PlaidAccount::Liabilities::MortgageProcessor.new(@plaid_account.reload, as_of: Date.new(2026, 1, 15))
+
+ assert_difference -> { DebugLogEntry.where(provider_key: "plaid").count }, 1, "the refusal must still be reported" do
+ writer.send(:write_loan_terms, rate_type: "variable", interest_rate: 5.2)
+ end
+
+ assert_equal "fixed", writer.send(:account).loan.rate_type,
+ "the rolled-back reclassification is still on the writer's loan in memory"
+ loan.reload
+ assert_equal "fixed", loan.rate_type, "the reclassification landed without its rate"
+ assert_equal 4.5, loan.interest_rate.to_f
+ assert_empty rates(loan)
+ assert_not DataEnrichment.exists?(enrichable: loan, attribute_name: "rate_type", source: "plaid")
+ end
+
+ test "a move to variable with an acceptable rate lands both" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "fixed", start_date: ORIGINATED)
+ writer = PlaidAccount::Liabilities::MortgageProcessor.new(@plaid_account.reload, as_of: Date.new(2026, 1, 15))
+
+ writer.send(:write_loan_terms, rate_type: "variable", interest_rate: 5.2)
+
+ loan.reload
+ assert_equal "variable", loan.rate_type
+ assert_equal({ "2026-01-15" => 5.2 }, rates(loan))
+ end
+
+ private
+ def loan_with(**attrs)
+ loan = @plaid_account.current_account.loan
+ loan.update!(attrs)
+ loan
+ end
+
+ # A loan that saves while fixed but is refused once its rate type turns
+ # variable: its recorded rate change predates its start date.
+ def loan_refusing_variable(rate_type: "fixed")
+ loan = loan_with(rate_type: rate_type, interest_rate: 4.5, start_date: Date.new(2020, 1, 1))
+ loan.update_columns(variable_rate_schedule: { "2019-06-01" => "4.0" })
+ loan
+ end
+
+ def payload(**interest_rate)
+ @plaid_account.update!(raw_liabilities_payload: { mortgage: { interest_rate: interest_rate } })
+ end
+
+ def process
+ PlaidAccount::Liabilities::MortgageProcessor.new(@plaid_account.reload).process
+ end
+
+ def process_as_of(date)
+ PlaidAccount::Liabilities::MortgageProcessor.new(@plaid_account.reload, as_of: date).process
+ end
+
+ # The schedule's value, not its stored representation.
+ def rates(loan)
+ (loan.variable_rate_schedule || {}).to_h { |date, rate| [ date.to_s, BigDecimal(rate.to_s).to_f ] }
+ end
end
diff --git a/test/models/plaid_account/liabilities/student_loan_processor_test.rb b/test/models/plaid_account/liabilities/student_loan_processor_test.rb
index 0fca641809..b1287e79a0 100644
--- a/test/models/plaid_account/liabilities/student_loan_processor_test.rb
+++ b/test/models/plaid_account/liabilities/student_loan_processor_test.rb
@@ -211,4 +211,87 @@ class PlaidAccount::Liabilities::StudentLoanProcessorTest < ActiveSupport::TestC
assert_nil loan.initial_balance
assert_nil loan.term_months
end
+
+ # This processor sends rate_type "fixed" on every sync, so a loan the user
+ # marked variable reverted each time.
+ test "a locked rate type is not forced back to fixed" do
+ loan = loan_with(rate_type: "variable", interest_rate: 5.0)
+ loan.lock_attr!(:rate_type)
+ payload("interest_rate_percentage" => 5.0)
+
+ process
+
+ assert_equal "variable", loan.reload.rate_type, "Plaid forced a locked rate type back to fixed"
+ end
+
+ # Locks hold per attribute: the unlocked terms in the same payload still land.
+ test "locked terms hold while the unlocked ones are still written" do
+ loan = loan_with(initial_balance: 50_000, term_months: 120, interest_rate: 5.0)
+ loan.lock_attr!(:initial_balance)
+ loan.lock_attr!(:term_months)
+ payload(
+ "interest_rate_percentage" => 6.5,
+ "origination_principal_amount" => 90_000,
+ "origination_date" => "2020-01-01",
+ "expected_payoff_date" => "2040-01-01"
+ )
+
+ process
+
+ loan.reload
+ assert_equal 50_000, loan.initial_balance.to_i, "a locked original balance was overwritten"
+ assert_equal 120, loan.term_months, "a locked term was overwritten"
+ assert_equal 6.5, loan.interest_rate.to_f, "the unlocked rate was not written"
+ end
+
+ # term_months is nil without both dates, and nil must not blank a stored term.
+ test "a payload missing a payoff date leaves the stored term alone" do
+ loan = loan_with(term_months: 120, interest_rate: 5.0)
+ payload("interest_rate_percentage" => 5.0, "origination_date" => "2020-01-01")
+
+ process
+
+ assert_equal 120, loan.reload.term_months, "an incomplete pair of dates blanked the stored term"
+ end
+
+ test "a payload without a rate leaves the stored rate alone" do
+ loan = loan_with(interest_rate: 4.5)
+ payload("origination_principal_amount" => 90_000)
+
+ process
+
+ assert_equal 4.5, loan.reload.interest_rate.to_f, "an omitted rate blanked the stored one"
+ assert_equal 90_000, loan.initial_balance.to_i
+ end
+
+ # The processor still sends rate_type "fixed", but a user's lock on
+ # "variable" holds, and the loan's rate change is then dated.
+ test "a student loan the user locked as variable has its rate change dated" do
+ loan = loan_with(interest_rate: 4.5, rate_type: "variable", start_date: Date.new(2020, 1, 1))
+ loan.lock_attr!(:rate_type)
+ payload("interest_rate_percentage" => 5.2)
+
+ PlaidAccount::Liabilities::StudentLoanProcessor.new(@plaid_account.reload, as_of: Date.new(2026, 1, 15)).process
+
+ loan.reload
+ assert_equal "variable", loan.rate_type
+ assert_equal 4.5, loan.interest_rate.to_f
+ assert_equal [ "2026-01-15" ], loan.variable_rate_schedule.keys
+ assert_equal BigDecimal("5.2"), BigDecimal(loan.variable_rate_schedule["2026-01-15"].to_s)
+ end
+
+ private
+ def loan_with(**attrs)
+ loan = @plaid_account.current_account.loan
+ loan.update!(attrs)
+ loan
+ end
+
+ def payload(data)
+ @plaid_account.update!(raw_liabilities_payload: { student: data })
+ end
+
+ def process
+ PlaidAccount::Liabilities::StudentLoanProcessor.new(@plaid_account.reload).process
+ end
end
diff --git a/test/models/plaid_account/processor_test.rb b/test/models/plaid_account/processor_test.rb
index afbe9f2474..ce9a581625 100644
--- a/test/models/plaid_account/processor_test.rb
+++ b/test/models/plaid_account/processor_test.rb
@@ -182,6 +182,38 @@ class PlaidAccount::ProcessorTest < ActiveSupport::TestCase
PlaidAccount::Processor.new(@plaid_account).process
end
+ # The loan processors date a rate change, so they are given the sync's date
+ # rather than reading the clock.
+ test "the sync date reaches the liability processor" do
+ expect_investment_product_processor_calls
+ expect_no_investment_balance_calculator_calls
+ expect_depository_product_processor_calls
+
+ @plaid_account.update!(plaid_type: "loan", plaid_subtype: "mortgage")
+ date = Date.new(2026, 1, 15)
+ mortgage = mock("mortgage_processor")
+ mortgage.expects(:process).once
+
+ PlaidAccount::Liabilities::MortgageProcessor.expects(:new).with(@plaid_account, as_of: date).returns(mortgage)
+
+ PlaidAccount::Processor.new(@plaid_account, as_of: date).process
+ end
+
+ test "the sync date reaches the student loan processor" do
+ expect_investment_product_processor_calls
+ expect_no_investment_balance_calculator_calls
+ expect_depository_product_processor_calls
+
+ @plaid_account.update!(plaid_type: "loan", plaid_subtype: "student")
+ date = Date.new(2026, 1, 15)
+ student_loan = mock("student_loan_processor")
+ student_loan.expects(:process).once
+
+ PlaidAccount::Liabilities::StudentLoanProcessor.expects(:new).with(@plaid_account, as_of: date).returns(student_loan)
+
+ PlaidAccount::Processor.new(@plaid_account, as_of: date).process
+ end
+
test "processes student loan liability data" do
expect_investment_product_processor_calls
expect_no_investment_balance_calculator_calls
diff --git a/test/models/plaid_item/syncer_test.rb b/test/models/plaid_item/syncer_test.rb
new file mode 100644
index 0000000000..c22afcd25b
--- /dev/null
+++ b/test/models/plaid_item/syncer_test.rb
@@ -0,0 +1,116 @@
+require "test_helper"
+
+class PlaidItem::SyncerTest < ActiveSupport::TestCase
+ setup do
+ @plaid_item = plaid_items(:one)
+ end
+
+ # A Plaid rate change is dated to the sync. The syncer reads the clock once
+ # and hands that date to the processing phase.
+ test "the processing phase is given the sync's date" do
+ dated = nil
+
+ travel_to Time.zone.local(2026, 1, 15, 12, 0, 0) do
+ @plaid_item.stubs(:import_latest_plaid_data)
+ @plaid_item.stubs(:schedule_account_syncs)
+ @plaid_item.expects(:process_accounts).with { |**kwargs| dated = kwargs[:as_of] }
+
+ PlaidItem::Syncer.new(@plaid_item).perform_sync(stub_sync)
+ end
+
+ assert_equal Date.new(2026, 1, 15), dated
+ end
+
+ # A background job runs in UTC. At 06:00 on 16 Jan in Sydney it is still the
+ # 15th in UTC, and a rate change dated the 15th would be charged from a period
+ # before the user saw it.
+ test "the sync's date is the family's date, not the job's" do
+ @plaid_item.family.update!(timezone: "Australia/Sydney")
+ dated = nil
+
+ travel_to Time.utc(2026, 1, 15, 19, 0, 0) do
+ @plaid_item.stubs(:import_latest_plaid_data)
+ @plaid_item.stubs(:schedule_account_syncs)
+ @plaid_item.expects(:process_accounts).with { |**kwargs| dated = kwargs[:as_of] }
+
+ PlaidItem::Syncer.new(@plaid_item).perform_sync(stub_sync)
+ end
+
+ assert_equal Date.new(2026, 1, 16), dated
+ end
+
+ test "process_accounts hands its date to every account's processor" do
+ date = Date.new(2026, 1, 15)
+ processor = mock("processor")
+ processor.stubs(:process)
+
+ assert_not_empty @plaid_item.plaid_accounts
+ @plaid_item.plaid_accounts.each do |plaid_account|
+ PlaidAccount::Processor.expects(:new).with(plaid_account, as_of: date).returns(processor)
+ end
+
+ @plaid_item.process_accounts(as_of: date)
+ end
+
+ # The chain end to end: the importer swallows ITEM_LOGIN_REQUIRED, the
+ # processing phase still runs, and the stored liabilities payload is last
+ # sync's. Its rate must not become a change dated today.
+ test "a sync whose import needed a fresh login dates no rate change" do
+ plaid_account = plaid_accounts(:one)
+ plaid_account.update!(plaid_type: "loan", plaid_subtype: "mortgage",
+ raw_liabilities_payload: { mortgage: { interest_rate: { type: "variable", percentage: 5.2 } } })
+ plaid_account.current_account.update!(accountable: Loan.new(interest_rate: 4.5, rate_type: "variable", start_date: Date.new(2020, 1, 1)))
+ loan = plaid_account.current_account.loan
+
+ provider = mock("Provider::Plaid")
+ provider.stubs(:get_item).raises(Plaid::ApiError.new(code: 400, response_body: { "error_code" => "ITEM_LOGIN_REQUIRED" }.to_json))
+ @plaid_item.stubs(:plaid_provider).returns(provider)
+ @plaid_item.stubs(:schedule_account_syncs)
+
+ PlaidItem::Syncer.new(@plaid_item).perform_sync(stub_sync)
+
+ assert_predicate @plaid_item.reload, :requires_update?
+ loan.reload
+ assert_empty loan.variable_rate_schedule || {}, "a stale payload's rate was dated as a change"
+ assert_equal 4.5, loan.interest_rate.to_f
+ end
+
+ # Plaid can stop returning an account, closed at the bank say. Its stored
+ # payload is then an earlier sync's, and must not be dated as a change.
+ test "an account Plaid leaves out of the sync dates no rate change" do
+ plaid_account = plaid_accounts(:one)
+ plaid_account.update!(plaid_type: "loan", plaid_subtype: "mortgage",
+ raw_liabilities_payload: { mortgage: { interest_rate: { type: "variable", percentage: 5.2 } } })
+ plaid_account.current_account.update!(accountable: Loan.new(interest_rate: 4.5, rate_type: "variable", start_date: Date.new(2020, 1, 1)))
+ loan = plaid_account.current_account.loan
+
+ provider = mock("Provider::Plaid")
+ provider.stubs(:get_item).returns(OpenStruct.new(item: OpenStruct.new(institution_id: "ins_1")))
+ provider.stubs(:get_institution).returns(OpenStruct.new(institution: OpenStruct.new))
+ @plaid_item.stubs(:plaid_provider).returns(provider)
+ @plaid_item.stubs(:upsert_plaid_snapshot!)
+ @plaid_item.stubs(:upsert_plaid_institution_snapshot!)
+ @plaid_item.stubs(:schedule_account_syncs)
+ PlaidItem::AccountsSnapshot.any_instance.stubs(:accounts).returns([])
+ PlaidItem::AccountsSnapshot.any_instance.stubs(:transactions_cursor).returns(nil)
+
+ PlaidItem::Syncer.new(@plaid_item).perform_sync(stub_sync)
+
+ loan.reload
+ assert_empty loan.variable_rate_schedule || {}, "a payload Plaid did not send this sync was dated as a change"
+ assert_equal 4.5, loan.interest_rate.to_f
+ assert_equal({}, plaid_account.reload.raw_liabilities_payload)
+ end
+
+ private
+ def stub_sync
+ sync = mock("sync")
+ sync.stubs(:respond_to?).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
diff --git a/test/models/redbark_account/loan_details_processor_test.rb b/test/models/redbark_account/loan_details_processor_test.rb
index 6f93a2c4b1..66622d8572 100644
--- a/test/models/redbark_account/loan_details_processor_test.rb
+++ b/test/models/redbark_account/loan_details_processor_test.rb
@@ -286,6 +286,17 @@ class RedbarkAccount::LoanDetailsProcessorTest < ActiveSupport::TestCase
assert_equal({ "2026-09-21" => BigDecimal("6.75") }, rates)
end
+ # The syncer dates a sync in the family's zone. A snapshot stamped at 19:00
+ # UTC on the 20th was fetched on the 21st in Sydney, so it is this sync's.
+ test "a snapshot is judged fresh on the family's calendar" do
+ @family.update!(timezone: "Australia/Sydney")
+ detail lendingRate: "0.0675", fetched_at: Time.utc(2026, 9, 20, 19, 0, 0)
+
+ 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
@@ -471,6 +482,25 @@ class RedbarkAccount::LoanDetailsProcessorTest < ActiveSupport::TestCase
assert_empty schedule
end
+ # The bound is checked on the percentage before it is rounded to three
+ # places, which would carry a reading just outside it onto 0 or 100.
+ test "a rate just outside the bound is not rounded into it" do
+ [ "-0.000004", "1.000004" ].each do |reported|
+ @loan.update_columns(variable_rate_schedule: {})
+ detail lendingRate: reported
+ assert_difference -> { DebugLogEntry.count }, 1, "#{reported} was not logged" do
+ process
+ end
+ assert_empty schedule, "#{reported} was recorded"
+ end
+ end
+
+ test "a rate just inside the ceiling rounds onto it and is recorded" do
+ detail lendingRate: "0.999996"
+ process
+ assert_equal({ "2026-09-21" => BigDecimal(100) }, rates)
+ 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"
diff --git a/test/models/redbark_item/syncer_test.rb b/test/models/redbark_item/syncer_test.rb
index 46e73d303c..b2c1618e8b 100644
--- a/test/models/redbark_item/syncer_test.rb
+++ b/test/models/redbark_item/syncer_test.rb
@@ -61,6 +61,25 @@ class RedbarkItem::SyncerTest < ActiveSupport::TestCase
"the import stamped one date and the processing dated its findings by another"
end
+ # The processing date is the family's, read from the same clock as the stamp.
+ # 19:00 UTC on the 20th is the 21st in Sydney.
+ test "the processing date is the family's date for the sync's clock" do
+ @family.update!(timezone: "Australia/Sydney")
+ dated = nil
+
+ travel_to Time.utc(2026, 9, 20, 19, 0, 0) do
+ @redbark_item.stubs(:import_latest_redbark_data).returns({})
+ @redbark_item.expects(:process_accounts).with { |**kwargs|
+ dated = kwargs[:as_of]
+ true
+ }.returns([])
+
+ @syncer.perform_sync(mock_sync)
+ end
+
+ assert_equal Date.new(2026, 9, 21), dated
+ end
+
private
def mock_sync