The personal finance app for everyone (by everyone)
Ruby
feat(goals): tell the user when a reserve has dropped below its level (#3175)
buzzromain90203139bfb3
diff --git a/app/helpers/insights_helper.rb b/app/helpers/insights_helper.rbindex 0d16285897..ac9aca1f71 100644--- a/app/helpers/insights_helper.rb+++ b/app/helpers/insights_helper.rb@@ -7,7 +7,10 @@ module InsightsHelper"savings_rate_change" => "piggy-bank","idle_cash" => "wallet","budget_at_risk" => "alert-triangle",- "budget_on_track" => "circle-check"+ "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"}.freezedef insight_icon_key(insight)@@ -111,6 +114,9 @@ module InsightsHelperwhen "budget_at_risk", "budget_on_track"return nil unless insight.period_start{ text: t("insights.actions.budget"), href: budget_path(Budget.date_to_param(insight.period_start)) }+ when "maintained_goal_depleted"+ goal = insight.family.goals.find_by(id: metadata["goal_id"])+ goal && { text: t("insights.actions.maintained_goal_depleted"), href: goal_path(goal) }endend@@ -152,7 +158,9 @@ module InsightsHelpermetadata["direction"] == "below" ? :positive : :warningwhen "cash_flow_warning"metadata["negative"] ? :negative : :warning- when "budget_at_risk"+ when "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.:warningelse:neutraldiff --git a/app/jobs/generate_insights_job.rb b/app/jobs/generate_insights_job.rbindex c9a36f6817..82e8f6a5f1 100644--- a/app/jobs/generate_insights_job.rb+++ b/app/jobs/generate_insights_job.rb@@ -127,7 +127,8 @@ class GenerateInsightsJob < ApplicationJob# The condition cleared earlier and has now returned with the same# numbers. Expiry was the system's doing, not the user's, so the# insight resurfaces; the body is still accurate, so no rewrite.- existing.update!(status: "active", facts: facts, generated_at: Time.current, read_at: nil)+ existing.update!(title: generated.title, status: "active", facts: facts,+ generated_at: Time.current, read_at: nil)existingelse# Same signal, same numbers: don't rewrite the body (avoids an LLM@@ -135,7 +136,13 @@ class GenerateInsightsJob < ApplicationJob# refresh — they're display values (key figure, link labels), and# keeping them current is exactly why they're not part of the# material-change comparison.- existing.update!(facts: facts, generated_at: Time.current)+ #+ # The title refreshes with them. It is built from I18n and the+ # generator's own data, not written by the model, so keeping it+ # current costs nothing — and a title naming a goal or a category+ # the user has since renamed is simply wrong on the page. Rename is+ # not a reason to resurface, so status and read state stay untouched.+ existing.update!(title: generated.title, facts: facts, generated_at: Time.current)nilendrescue ActiveRecord::RecordNotUniquediff --git a/app/models/insight.rb b/app/models/insight.rbindex 21fb6052c1..15969f13e5 100644--- a/app/models/insight.rb+++ b/app/models/insight.rb@@ -26,6 +26,7 @@ class Insight < ApplicationRecordidle_cashbudget_at_riskbudget_on_track+ maintained_goal_depleted].freeze# How many the dashboard widget shows. Shared so PagesController (first render)diff --git a/app/models/insight/generator_registry.rb b/app/models/insight/generator_registry.rbindex 3fb9287926..968d257cf0 100644--- a/app/models/insight/generator_registry.rb+++ b/app/models/insight/generator_registry.rb@@ -11,7 +11,8 @@ class Insight::GeneratorRegistryInsight::Generators::SubscriptionAuditGenerator,Insight::Generators::SavingsRateChangeGenerator,Insight::Generators::IdleCashGenerator,- Insight::Generators::BudgetInsightGenerator+ Insight::Generators::BudgetInsightGenerator,+ Insight::Generators::MaintainedGoalDepletedGenerator].freezeResult = Data.define(:insights, :succeeded_types)diff --git a/app/models/insight/generators/maintained_goal_depleted_generator.rb b/app/models/insight/generators/maintained_goal_depleted_generator.rbnew file mode 100644index 0000000000..9584218ebf--- /dev/null+++ b/app/models/insight/generators/maintained_goal_depleted_generator.rb@@ -0,0 +1,59 @@+# Flags a reserve that has fallen below the level it exists to hold.+#+# High priority, unlike most of this feed. `IdleCashGenerator` is a nudge about+# money doing nothing; this is the opposite — a floor the user deliberately set+# is no longer there, and the whole point of a maintained goal is that someone+# says so. It is the one signal a reserve produces that a one-off goal cannot.+#+# The dedup key rotates monthly: a reserve can sit short for weeks while the+# user rebuilds it, and re-raising the same shortfall every night would train+# them to dismiss the feed.+class Insight::Generators::MaintainedGoalDepletedGenerator < Insight::Generator+ produces "maintained_goal_depleted"++ # A family running several drained reserves has one problem, not four. Past+ # the first couple the feed stops informing and starts scolding.+ MAX_INSIGHTS = 2++ def generate+ depleted_reserves.first(MAX_INSIGHTS).map do |goal|+ missing = goal.remaining_amount_money++ build_insight(+ insight_type: "maintained_goal_depleted",+ priority: "high",+ title: I18n.t("insights.titles.maintained_goal_depleted", goal: goal.name),+ template_key: "maintained_goal_depleted",+ facts: {+ goal: goal.name,+ missing: missing.format,+ saved: goal.current_balance_money.format,+ target: goal.target_amount_money.format+ },+ metadata: {+ goal_id: goal.id,+ missing: round(missing.amount, 0),+ target: round(goal.target_amount, 0)+ },+ dedup_key: "maintained_goal_depleted:#{goal.id}:#{month_token}"+ )+ end+ end++ private+ # Active only: a paused reserve is one the user shelved on purpose, and+ # `behind_pace?` already excludes paused goals for the same reason —+ # nagging about a goal someone deliberately put down is noise.+ #+ # Loaded through `Goal.prepared_for`, which injects the family-wide pooled+ # allocations once. Asking each goal for its status reaches `current_balance`,+ # and without that injection every reserve would re-read the whole pool.+ #+ # Ordered by shortfall so a tight MAX_INSIGHTS spends itself on the reserves+ # furthest from their floor, and stays stable between nightly runs.+ def depleted_reserves+ Goal.prepared_for(family, scope: family.goals.where(kind: "maintained", state: "active"))+ .select { |goal| goal.status == :depleted }+ .sort_by { |goal| -goal.remaining_amount.to_d }+ end+enddiff --git a/config/locales/views/insights/en.yml b/config/locales/views/insights/en.ymlindex d47cd2372d..3f5f9585cc 100644--- a/config/locales/views/insights/en.yml+++ b/config/locales/views/insights/en.yml@@ -33,6 +33,7 @@ en:idle_cash: Idle cashbudget_at_risk: Budgetbudget_on_track: Budget+ maintained_goal_depleted: Reservemeta:next_n_days:one: Next day@@ -61,6 +62,7 @@ en:savings_rate_change: View that month's transactionsidle_cash: Go to accountbudget: View budget+ maintained_goal_depleted: View reservetitles:spending_anomaly:above: "%{category} spending is trending up"@@ -69,6 +71,7 @@ en:low: Your cash balance may run lownegative: Your cash balance may go negativenet_worth_milestone: "Net worth milestone: %{milestone}"+ maintained_goal_depleted: "%{goal} has dropped below its level"subscription_audit: "Is %{name} still active?"savings_rate_change:up: Your savings rate improved in %{month}@@ -86,6 +89,7 @@ en:low: Based on your upcoming recurring transactions and typical spending, your cash balance could drop to %{projected_low} around %{projected_low_date}.negative: Based on your upcoming recurring transactions and typical spending, your cash balance could fall to %{projected_low} around %{projected_low_date}.net_worth_milestone: Your net worth crossed %{milestone} and now stands at %{net_worth}.+ maintained_goal_depleted: "%{goal} holds %{saved} of the %{target} it is meant to keep. It is %{missing} short."subscription_audit: "%{name} (%{amount}) hasn't appeared since it was expected on %{expected_on}. It may have been cancelled, or the charge may have moved."savings_rate_change:up: You saved %{current_rate}% of your income in %{month}, up %{change_pp} percentage points from %{previous_rate}% the month before.diff --git a/config/locales/views/insights/fr.yml b/config/locales/views/insights/fr.ymlindex 611ebfd525..e65d312fbe 100644--- a/config/locales/views/insights/fr.yml+++ b/config/locales/views/insights/fr.yml@@ -8,6 +8,7 @@ fr:budget: Voir le budgetcash_flow_warning: Vérifier les transactions récurrentesidle_cash: Aller au compte+ maintained_goal_depleted: Voir la réservenet_worth_milestone: Voir le rapport de patrimoine netsavings_rate_change: Voir les transactions de ce moisspending_anomaly: Voir les transactions de %{category}@@ -59,6 +60,7 @@ fr:%{budget_spent_pct}% de votre budget total jusqu'à présent."budget_on_track: Vous avez dépensé %{spent} sur votre budget de %{budgeted}(%{budget_spent_pct}%) et tout reste dans les limites.+ maintained_goal_depleted: "%{goal} détient %{saved} sur les %{target} qu'elle doit conserver. Il manque %{missing}."cash_flow_warning:low: D'après vos prochaines transactions récurrentes et vos dépenses habituelles,votre solde de trésorerie pourrait descendre à %{projected_low} vers le@@ -97,6 +99,7 @@ fr:cash_flow_warning:low: Votre solde de trésorerie pourrait devenir faiblenegative: Votre solde de trésorerie pourrait devenir négatif+ maintained_goal_depleted: "%{goal} est passée sous son niveau"idle_cash: Liquidités inactives sur %{account}net_worth_milestone: "Étape de patrimoine net : %{milestone}"savings_rate_change:@@ -111,6 +114,7 @@ fr:budget_on_track: Budgetcash_flow_warning: Trésorerieidle_cash: Liquidités inactives+ maintained_goal_depleted: Réservenet_worth_milestone: Patrimoine netsavings_rate_change: Taux d'épargnespending_anomaly: Dépensesdiff --git a/test/jobs/generate_insights_job_test.rb b/test/jobs/generate_insights_job_test.rbindex 3af4f053ea..144138d0bd 100644--- a/test/jobs/generate_insights_job_test.rb+++ b/test/jobs/generate_insights_job_test.rb@@ -153,6 +153,39 @@ class GenerateInsightsJobTest < ActiveJob::TestCaseassert insight.read?end+ # The title is built from I18n and the generator's own data, not written by+ # the model. A goal or category renamed since the insight was stored left it+ # naming something that no longer exists, for the rest of the month.+ test "a renamed subject refreshes the title without resurfacing the insight" do+ stub_generated([ generated_insight ])+ GenerateInsightsJob.perform_now(family_id: @family.id)++ insight = @family.insights.find_by(dedup_key: "idle_cash:test-account:2026-07")+ original_body = insight.body+ insight.mark_read!++ stub_generated([ generated_insight(title: "Idle cash in Holiday Fund") ])+ GenerateInsightsJob.perform_now(family_id: @family.id)++ insight.reload+ assert_equal "Idle cash in Holiday Fund", insight.title+ assert_equal original_body, insight.body, "a rename is not worth an LLM rewrite"+ assert insight.read?, "a rename is not a reason to nag the user again"+ end+ test "a reactivated insight also picks up a renamed subject" do+ stub_generated([ generated_insight ])+ GenerateInsightsJob.perform_now(family_id: @family.id)++ insight = @family.insights.find_by(dedup_key: "idle_cash:test-account:2026-07")+ insight.update!(status: "expired")++ stub_generated([ generated_insight(title: "Idle cash in Holiday Fund") ])+ GenerateInsightsJob.perform_now(family_id: @family.id)++ insight.reload+ assert insight.active?+ assert_equal "Idle cash in Holiday Fund", insight.title+ endtest "acknowledged insight stays acknowledged when numbers are unchanged" dostub_generated([ generated_insight ])GenerateInsightsJob.perform_now(family_id: @family.id)@@ -256,11 +289,11 @@ class GenerateInsightsJobTest < ActiveJob::TestCase# display_balance changes only the formatted facts, leaving metadata (the# material-change signal) untouched — mirrors a balance drifting slightly# between runs without crossing a bucket boundary.- def generated_insight(balance: 5000.0, display_balance: nil)+ def generated_insight(balance: 5000.0, display_balance: nil, title: "Idle cash in Test Checking")Insight::Generator::GeneratedInsight.new(insight_type: "idle_cash",priority: "low",- title: "Idle cash in Test Checking",+ title: title,template_key: "idle_cash",facts: { account: "Test Checking", balance: "$#{(display_balance || balance).to_i}", idle_days: 60 },metadata: { account_id: "test-account", balance: balance },diff --git a/test/models/insight/generators/maintained_goal_depleted_generator_test.rb b/test/models/insight/generators/maintained_goal_depleted_generator_test.rbnew file mode 100644index 0000000000..bec74be784--- /dev/null+++ b/test/models/insight/generators/maintained_goal_depleted_generator_test.rb@@ -0,0 +1,87 @@+require "test_helper"++class Insight::Generators::MaintainedGoalDepletedGeneratorTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ end++ test "flags a reserve that has fallen below its level" do+ goal = reserve(name: "Precaution", balance: 4_000, target: 6_000)++ insights = generate++ assert_equal 1, insights.size+ insight = insights.first+ assert_equal "maintained_goal_depleted", insight.insight_type+ assert_equal "high", insight.priority+ assert_equal goal.id, insight.metadata[:goal_id]+ assert_equal 2_000, insight.metadata[:missing]+ end++ test "says nothing about a reserve sitting at its level" do+ reserve(name: "Whole", balance: 6_000, target: 6_000)++ assert_empty generate+ end++ # A paused reserve is one the user shelved on purpose. `behind_pace?` excludes+ # paused goals for the same reason: nagging about a goal someone deliberately+ # put down is noise, not a signal.+ test "says nothing about a reserve the user paused" do+ reserve(name: "Shelved", balance: 1_000, target: 6_000).pause!++ assert_empty generate+ end++ test "ignores one-off goals, however short they are" do+ account = fresh_account(0)+ @family.goals.create!(name: "Trip", target_amount: 5_000, currency: "USD") do |g|+ g.goal_accounts.build(account: account)+ end++ assert_empty generate+ end++ # The dedup key rotates monthly: a reserve can sit short for weeks while the+ # user rebuilds it, and re-raising the same shortfall nightly would train them+ # to dismiss the feed.+ test "the dedup key carries the goal and the month" do+ goal = reserve(name: "Precaution", balance: 4_000, target: 6_000)++ assert_equal "maintained_goal_depleted:#{goal.id}:#{Date.current.strftime('%Y-%m')}",+ generate.first.dedup_key+ end++ # A family running several drained reserves has one problem, not four.+ test "caps how many it raises, worst shortfall first" do+ reserve(name: "Small gap", balance: 5_000, target: 6_000)+ reserve(name: "Big gap", balance: 1_000, target: 9_000)+ reserve(name: "Middle gap", balance: 3_000, target: 6_000)++ insights = generate++ assert_equal 2, insights.size+ assert_equal [ 8_000, 3_000 ], insights.map { |i| i.metadata[:missing] }+ end++ private+ def generate+ Insight::Generators::MaintainedGoalDepletedGenerator.new(@family).generate+ end++ # A dedicated account each time: the fixtures already have goals claiming+ # `depository`, and a shared one would drag the pro-rata haircut into every+ # shortfall figure asserted here.+ def fresh_account(balance)+ Account.create!(+ family: @family, accountable: Depository.new,+ name: "Pot #{SecureRandom.hex(4)}", currency: "USD", balance: balance+ )+ end++ def reserve(name:, balance:, target:)+ @family.goals.create!(name: name, target_amount: target, currency: "USD", kind: "maintained") do |g|+ g.goal_accounts.build(account: fresh_account(balance))+ end+ end+end