The personal finance app for everyone (by everyone)
Ruby
Add an insight for upcoming loan payment changes (#5171)
David Gil6db9b682d62f
diff --git a/app/helpers/insights_helper.rb b/app/helpers/insights_helper.rbindex d274e48fbe..3cd10e7e43 100644--- a/app/helpers/insights_helper.rb+++ b/app/helpers/insights_helper.rb@@ -10,7 +10,8 @@ module InsightsHelper"budget_on_track" => "circle-check",# Same shield the reserve panel uses on the goal page, so the two read as# the same object seen from two places.- "maintained_goal_depleted" => "shield-alert"+ "maintained_goal_depleted" => "shield-alert",+ "loan_payment_change" => "landmark"}.freezedef insight_icon_key(insight)@@ -81,6 +82,8 @@ module InsightsHelperwhen "budget_on_track"# Still the right figure here, where overall usage *is* the subject.facts["budget_spent_pct"] && [ "#{facts["budget_spent_pct"]}%", t("insights.figures.of_budget") ]+ when "loan_payment_change"+ facts["new_payment"] && [ facts["new_payment"], facts["effective_on"] ]endend@@ -98,9 +101,9 @@ module InsightsHelpertext: t("insights.actions.spending_anomaly", category: category.name),href: transactions_path(q: { categories: [ category.name ] })}- when "idle_cash"+ when "idle_cash", "loan_payment_change"account = insight.family.accounts.visible.find_by(id: metadata["account_id"])- account && { text: t("insights.actions.idle_cash"), href: account_path(account) }+ account && { text: t("insights.actions.#{insight.insight_type}"), href: account_path(account) }when "subscription_audit"{ text: t("insights.actions.subscription_audit"), href: recurring_transactions_path }when "cash_flow_warning"@@ -181,6 +184,8 @@ module InsightsHelpermetadata["direction"] == "below" ? :positive : :warningwhen "cash_flow_warning"metadata["negative"] ? :negative : :warning+ when "loan_payment_change"+ metadata["new_payment"].to_f < metadata["previous_payment"].to_f ? :positive : :warningwhen "budget_at_risk", "maintained_goal_depleted"# Warning, not negative: the reserve is short, not overdrawn, and red is# reserved here for money actually going the wrong side of zero.diff --git a/app/jobs/generate_insights_job.rb b/app/jobs/generate_insights_job.rbindex 590f4e1df1..3a7f7f84e8 100644--- a/app/jobs/generate_insights_job.rb+++ b/app/jobs/generate_insights_job.rb@@ -18,7 +18,7 @@ class GenerateInsightsJob < ApplicationJobprivate# Insights are a preview feature, so the nightly sweep only visits families# with an opted-in member. Unlike a job that moves existing data around,- # this one manufactures data per family — seven generators over the income+ # this one manufactures data per family — every generator, most of them over the income# statement and balance sheet — so running it for# families who can't see the result is pure waste. Scoped in SQL rather# than checked per family to keep the fan-out a single indexed query.diff --git a/app/models/insight.rb b/app/models/insight.rbindex 3c0340dd6f..264bb18dd5 100644--- a/app/models/insight.rb+++ b/app/models/insight.rb@@ -9,7 +9,7 @@# "Acknowledged" rather than "dismissed" because that is what the state has# always actually meant. GenerateInsightsJob resurfaces a row whose bucketed# metadata changes materially even if the user acknowledged the stale version,-# and 6 of 8 generators scope `dedup_key` to a month, so acknowledging July's+# and most generators scope `dedup_key` to a month, so acknowledging July's# budget card says nothing about August's. The contract is: acknowledgement# covers the numbers you saw; new numbers are a new insight. The DB value stays# `"dismissed"` (and the `dismissed_at` column keeps its name) so this needed no@@ -27,6 +27,7 @@ class Insight < ApplicationRecordbudget_at_riskbudget_on_trackmaintained_goal_depleted+ loan_payment_change].freeze# How many the dashboard widget shows. Shared so PagesController (first render)diff --git a/app/models/insight/generator.rb b/app/models/insight/generator.rbindex 61c89deeae..f115f67318 100644--- a/app/models/insight/generator.rb+++ b/app/models/insight/generator.rb@@ -118,4 +118,10 @@ class Insight::Generatordef signed_number(value)value.negative? ? "−#{value.abs}" : value.to_send++ # A display fact rounded to one decimal with the locale's separator, so+ # Spanish copy reads "35,0" rather than "35.0".+ def decimal_fact(value)+ ActiveSupport::NumberHelper.number_to_rounded(round(value, 1), precision: 1)+ endenddiff --git a/app/models/insight/generator_registry.rb b/app/models/insight/generator_registry.rbindex 968d257cf0..84fbf89a98 100644--- a/app/models/insight/generator_registry.rb+++ b/app/models/insight/generator_registry.rb@@ -12,7 +12,8 @@ class Insight::GeneratorRegistryInsight::Generators::SavingsRateChangeGenerator,Insight::Generators::IdleCashGenerator,Insight::Generators::BudgetInsightGenerator,- Insight::Generators::MaintainedGoalDepletedGenerator+ Insight::Generators::MaintainedGoalDepletedGenerator,+ Insight::Generators::LoanRepaymentChangeGenerator].freezeResult = Data.define(:insights, :succeeded_types)diff --git a/app/models/insight/generators/loan_repayment_change_generator.rb b/app/models/insight/generators/loan_repayment_change_generator.rbnew file mode 100644index 0000000000..452ba94a5b--- /dev/null+++ b/app/models/insight/generators/loan_repayment_change_generator.rb@@ -0,0 +1,98 @@+# Warns ahead of a change in a loan's scheduled repayment: a rate change the+# user recorded, the end of a fixed period entered as one, or anything else+# the loan's own schedule re-amortises at. It reads Loan#amortization_schedule+# and nothing else, so the figures are the ones the loan page shows, built+# from the terms the user entered. No market rate is guessed.+#+# Named "Repayment" while the type stays loan_payment_change: in CamelCase,+# "LoanPaymentChange..." matches the CI secret scanner's AWS key pattern.+#+# The dedup key carries the effective date, so each change is its own insight,+# and it expires by itself once that date has passed.+class Insight::Generators::LoanRepaymentChangeGenerator < Insight::Generator+ produces "loan_payment_change"++ HORIZON_DAYS = 60+ MIN_CHANGE_PCT = 3+ HIGH_PRIORITY_PCT = 10++ def generate+ shared_loan_accounts.filter_map do |account|+ previous, upcoming = upcoming_change(account.loan)+ change_insight(account, previous, upcoming) if upcoming+ end+ end++ private+ # The insight names the loan, so only loans every active member can see+ # qualify, as for IdleCashGenerator. Ordered so the feed is stable.+ def shared_loan_accounts+ family.accounts.visible.accessible_by_all_active_members+ .where(accountable_type: "Loan")+ .includes(:accountable)+ .order(:created_at, :id)+ end++ # The first payment inside the horizon that differs from the one before it+ # by at least MIN_CHANGE_PCT, with that previous payment. The previous one+ # may already be paid: a payment changing on the 10th changes from the one+ # made last month. The final payment is left out, since it only absorbs+ # the schedule's rounding.+ def upcoming_change(loan)+ payments = loan.amortization_schedule&.payments+ return if payments.blank?++ horizon = Date.current..(Date.current + HORIZON_DAYS)+ payments[0...-1].each_cons(2).find do |previous, upcoming|+ horizon.cover?(upcoming.date) && change_pct(previous, upcoming).abs >= MIN_CHANGE_PCT+ end+ end++ def change_pct(previous, upcoming)+ before = previous.payment.amount+ return 0 unless before.positive?++ (upcoming.payment.amount - before) / before * 100+ end++ def change_insight(account, previous, upcoming)+ pct = change_pct(previous, upcoming)+ direction = pct.positive? ? "up" : "down"++ build_insight(+ insight_type: "loan_payment_change",+ priority: priority_for(pct),+ title: I18n.t("insights.titles.loan_payment_change.#{direction}", account: account.name),+ template_key: "loan_payment_change.#{direction}",+ facts: {+ account: account.name,+ previous_payment: previous.payment.format,+ new_payment: upcoming.payment.format,+ effective_on: I18n.l(upcoming.date, format: :short),+ change_pct: decimal_fact(pct.abs)+ },+ # Deterministic from the loan's terms: these move only when the user+ # edits the loan, which is exactly when the insight should resurface.+ metadata: {+ account_id: account.id,+ effective_on: upcoming.date.iso8601,+ previous_payment: payment_amount(previous),+ new_payment: payment_amount(upcoming)+ },+ dedup_key: "loan_payment_change:#{account.id}:#{upcoming.date.iso8601}"+ )+ end++ # At the loan currency's own precision: rounding a three-decimal payment+ # to two would hide small changes and read some drops as no change.+ def payment_amount(payment)+ round(payment.payment.amount, payment.payment.currency.default_precision)+ end++ # A lower payment is good news, so it sits at the bottom of the feed.+ def priority_for(pct)+ return "low" if pct.negative?++ pct >= HIGH_PRIORITY_PCT ? "high" : "medium"+ end+enddiff --git a/config/locales/views/insights/en.yml b/config/locales/views/insights/en.ymlindex 510d502cf2..a359cb3395 100644--- a/config/locales/views/insights/en.yml+++ b/config/locales/views/insights/en.yml@@ -46,6 +46,7 @@ en:budget_at_risk: Budgetbudget_on_track: Budgetmaintained_goal_depleted: Reserve+ loan_payment_change: Loan paymentmeta:next_n_days:one: Next day@@ -75,6 +76,7 @@ en:idle_cash: Go to accountbudget: View budgetmaintained_goal_depleted: View reserve+ loan_payment_change: View loantitles:spending_anomaly:above: "%{category} spending is trending up"@@ -93,6 +95,9 @@ en:one: One category needs attention in your budgetother: "%{count} categories need attention in your budget"budget_on_track: Your budget is on track+ loan_payment_change:+ up: "%{account} payment is going up"+ down: "%{account} payment is going down"templates:spending_anomaly:above: You're on pace to spend %{projected_spend} on %{category} this month, about %{deviation_pct}% more than your recent monthly average of %{baseline_spend}.@@ -112,3 +117,6 @@ en:over: "%{categories} went over budget this month. You've used %{budget_spent_pct}% of your total budget so far."near: "%{categories} are close to their limits this month. You've used %{budget_spent_pct}% of your total budget so far."budget_on_track: You've spent %{spent} of your %{budgeted} budget (%{budget_spent_pct}%) and everything is within its limit.+ loan_payment_change:+ up: "Your %{account} payment changes from %{previous_payment} to %{new_payment} on %{effective_on}, %{change_pct}% more, according to the loan's schedule and its recorded rates."+ down: "Your %{account} payment changes from %{previous_payment} to %{new_payment} on %{effective_on}, %{change_pct}% less, according to the loan's schedule and its recorded rates."diff --git a/config/locales/views/insights/es.yml b/config/locales/views/insights/es.ymlindex b77b0336b5..68704a2099 100644--- a/config/locales/views/insights/es.yml+++ b/config/locales/views/insights/es.yml@@ -46,6 +46,7 @@ es:budget_at_risk: Presupuestobudget_on_track: Presupuestomaintained_goal_depleted: Reserva+ loan_payment_change: Cuota del préstamometa:next_n_days:one: Próximo día@@ -75,6 +76,7 @@ es:idle_cash: Ir a la cuentabudget: Ver presupuestomaintained_goal_depleted: Ver reserva+ loan_payment_change: Ver préstamotitles:spending_anomaly:above: El gasto en %{category} va en aumento@@ -93,6 +95,9 @@ es:one: Una categoría necesita atención en tu presupuestoother: "%{count} categorías necesitan atención en tu presupuesto"budget_on_track: Tu presupuesto va según lo previsto+ loan_payment_change:+ up: La cuota de %{account} va a subir+ down: La cuota de %{account} va a bajartemplates:spending_anomaly:above: Vas camino de gastar %{projected_spend} en %{category} este mes, aproximadamente un %{deviation_pct}% más que tu promedio mensual reciente de %{baseline_spend}.@@ -112,3 +117,6 @@ es:over: "%{categories} superaron el presupuesto este mes. Has usado el %{budget_spent_pct}% de tu presupuesto total hasta ahora."near: "%{categories} están cerca de sus límites este mes. Has usado el %{budget_spent_pct}% de tu presupuesto total hasta ahora."budget_on_track: Has gastado %{spent} de tu presupuesto de %{budgeted} (%{budget_spent_pct}%) y todo está dentro de su límite.+ loan_payment_change:+ up: "La cuota de %{account} pasa de %{previous_payment} a %{new_payment} el %{effective_on}, un %{change_pct}% más, según el cuadro de amortización y los tipos registrados."+ down: "La cuota de %{account} pasa de %{previous_payment} a %{new_payment} el %{effective_on}, un %{change_pct}% menos, según el cuadro de amortización y los tipos registrados."diff --git a/test/helpers/insights_helper_test.rb b/test/helpers/insights_helper_test.rbindex 43991760fd..68a059d667 100644--- a/test/helpers/insights_helper_test.rb+++ b/test/helpers/insights_helper_test.rb@@ -240,6 +240,19 @@ class InsightsHelperTest < ActionView::TestCaseassert_not insight_dig_in_available?(insight)end+ test "loan payment change reads its direction for sentiment and leads with the new payment" do+ up = build_insight("loan_payment_change",+ metadata: { "account_id" => accounts(:loan).id, "previous_payment" => 1424.0, "new_payment" => 1616.0 },+ facts: { "new_payment" => "$1,616.00", "effective_on" => "Dec 10", "account" => "Mortgage" })+ down = build_insight("loan_payment_change", metadata: { "previous_payment" => 1616.0, "new_payment" => 1424.0 })++ assert_equal :warning, insight_sentiment(up)+ assert_equal :positive, insight_sentiment(down)+ assert_equal [ "$1,616.00", "Dec 10" ], insight_key_figure(up)+ assert_equal account_path(accounts(:loan)), insight_action(up)[:href]+ assert_equal "Loan payment · Mortgage", insight_meta_line(up)+ end+privatedef build_insight(insight_type, priority: "medium", metadata: {}, facts: {}, period_start: nil, period_end: nil)Insight.new(diff --git a/test/models/insight/generators/loan_repayment_change_generator_test.rb b/test/models/insight/generators/loan_repayment_change_generator_test.rbnew file mode 100644index 0000000000..27a7b004e4--- /dev/null+++ b/test/models/insight/generators/loan_repayment_change_generator_test.rb@@ -0,0 +1,144 @@+require "test_helper"++class Insight::Generators::LoanRepaymentChangeGeneratorTest < ActiveSupport::TestCase+ setup do+ travel_to Date.new(2026, 11, 20)+ @family = families(:dylan_family)+ @account = accounts(:loan)+ # The fixture loan is private to the admin; most cases need it shared.+ @share = AccountShare.create!(account: @account, user: users(:family_member), permission: "read_only")+ @account.loan.update!(+ rate_type: "variable", interest_rate: 3.0, term_months: 300, initial_balance: 250_000,+ start_date: Date.new(2025, 12, 10), variable_rate_schedule: { "2026-12-10" => "4.5" }+ )+ end++ test "flags a recorded rate change that resizes the payment within 60 days" do+ insight = generate.sole+ payments = @account.loan.amortization_schedule.payments+ before = payments.find { |payment| payment.date == Date.new(2026, 11, 10) }.payment+ after = payments.find { |payment| payment.date == Date.new(2026, 12, 10) }.payment++ assert_equal "loan_payment_change", insight.insight_type+ assert_equal "loan_payment_change:#{@account.id}:2026-12-10", insight.dedup_key+ assert_equal "loan_payment_change.up", insight.template_key+ assert_equal({ account_id: @account.id, effective_on: "2026-12-10",+ previous_payment: before.amount.to_f, new_payment: after.amount.to_f }, insight.metadata)+ assert_equal before.format, insight.facts[:previous_payment]+ assert_equal after.format, insight.facts[:new_payment]+ assert_equal @account.name, insight.facts[:account]+ end++ test "stops emitting the change once its date has passed, so the job expires it" do+ travel_to Date.new(2026, 12, 11)++ assert_empty generate+ end++ test "ignores a change further out than 60 days" do+ @account.loan.update!(variable_rate_schedule: { "2027-02-10" => "4.5" })++ assert_empty generate+ end++ test "the window includes day 60 and excludes day 61" do+ stub_payments([ 1_000, Date.new(2026, 11, 10) ], [ 1_100, Date.new(2027, 1, 19) ], [ 1_100, Date.new(2027, 2, 19) ])+ assert_equal "2027-01-19", generate.sole.metadata[:effective_on]++ stub_payments([ 1_000, Date.new(2026, 11, 10) ], [ 1_100, Date.new(2027, 1, 20) ], [ 1_100, Date.new(2027, 2, 20) ])+ assert_empty generate+ end++ test "a change of exactly 3 percent is flagged and one just under is not" do+ stub_payments([ 1_000, Date.new(2026, 11, 10) ], [ 1_030, Date.new(2026, 12, 10) ], [ 1_030, Date.new(2027, 1, 10) ])+ assert_equal 1_030.0, generate.sole.metadata[:new_payment]++ stub_payments([ 1_000, Date.new(2026, 11, 10) ], [ 1_029.99, Date.new(2026, 12, 10) ], [ 1_029.99, Date.new(2027, 1, 10) ])+ assert_empty generate+ end++ test "a lower payment reads as good news at low priority" do+ stub_payments([ 1_616, Date.new(2026, 11, 10) ], [ 1_424, Date.new(2026, 12, 10) ], [ 1_424, Date.new(2027, 1, 10) ])++ insight = generate.sole++ assert_equal "loan_payment_change.down", insight.template_key+ assert_equal "low", insight.priority+ end++ test "a payment rise of 10 percent or more is high priority" do+ stub_payments([ 1_424, Date.new(2026, 11, 10) ], [ 1_616, Date.new(2026, 12, 10) ], [ 1_616, Date.new(2027, 1, 10) ])++ assert_equal "high", generate.sole.priority+ end++ test "keeps the payment precision of a currency with three decimals" do+ stub_payments([ 0.010, Date.new(2026, 11, 10) ], [ 0.009, Date.new(2026, 12, 10) ], [ 0.009, Date.new(2027, 1, 10) ],+ currency: "KWD")++ insight = generate.sole++ assert_equal "loan_payment_change.down", insight.template_key+ assert_equal({ previous_payment: 0.01, new_payment: 0.009 }, insight.metadata.slice(:previous_payment, :new_payment))+ end++ test "the final payment absorbing rounding is not a change" do+ stub_payments([ 1_000, Date.new(2026, 11, 10) ], [ 400, Date.new(2026, 12, 10) ])++ assert_empty generate+ end++ test "a fixed loan with a level payment produces nothing" do+ @account.loan.update!(rate_type: "fixed", variable_rate_schedule: {})++ assert_empty generate+ end++ test "a loan without the terms to build a schedule produces nothing" do+ @account.loan.update!(term_months: nil)++ assert_empty generate+ end++ test "a family without loans produces nothing" do+ @account.destroy!++ assert_empty generate+ end++ test "skips a loan that is private to one member" do+ @share.destroy!++ assert_empty generate+ end++ test "writes the body in English and Spanish" do+ %i[en es].each do |locale|+ I18n.with_locale(locale) do+ insight = generate.sole+ body = Insight::BodyWriter.new.write(insight)++ assert_includes body, @account.name+ assert_includes body, { en: "16.5%", es: "16,5%" }.fetch(locale)+ assert_no_match(/translation missing/i, body)+ assert_no_match(/translation missing/i, insight.title)+ end+ end+ end++ private+ def generate+ Insight::Generators::LoanRepaymentChangeGenerator.new(@family).generate+ end++ # A schedule reduced to what the generator reads: [amount, date] per payment.+ def stub_payments(*rows, currency: "USD")+ payments = rows.each_with_index.map do |(amount, date), index|+ money = Money.new(amount, currency)+ Loan::AmortizationSchedule::Payment.new(number: index + 1, date: date, payment: money,+ principal: money, interest: Money.new(0, currency),+ ending_balance: Money.new(0, currency))+ end+ Loan.any_instance.stubs(:amortization_schedule).returns(stub(payments: payments))+ end+end