Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add an insight for bills the paying account will not cover (#5166)

David Gil4362c27b77a3
diff --git a/app/helpers/insights_helper.rb b/app/helpers/insights_helper.rb
index 0a4ca16c0c..394ffe6440 100644
--- a/app/helpers/insights_helper.rb
+++ b/app/helpers/insights_helper.rb
@@ -11,6 +11,7 @@ module InsightsHelper
# 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",
+ "bill_not_covered" => "calendar-x",
"loan_payment_change" => "landmark"
}.freeze
@@ -82,6 +83,8 @@ module InsightsHelper
when "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 "bill_not_covered"
+ facts["shortfall"] && [ facts["shortfall"], t("insights.figures.short_on", date: facts["due_on"]) ]
when "loan_payment_change"
facts["new_payment"] && [ facts["new_payment"], facts["effective_on"] ]
end
@@ -101,8 +104,8 @@ module InsightsHelper
text: t("insights.actions.spending_anomaly", category: category.name),
href: transactions_path(q: { categories: [ category.name ] })
}
- when "idle_cash", "loan_payment_change"
- account = insight.family.accounts.visible.find_by(id: metadata["account_id"])
+ when "idle_cash", "bill_not_covered", "loan_payment_change"
+ account = insight_account(insight)
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 }
@@ -184,6 +187,9 @@ module InsightsHelper
metadata["direction"] == "below" ? :positive : :warning
when "cash_flow_warning"
metadata["negative"] ? :negative : :warning
+ when "bill_not_covered"
+ # Paying the bill would take the account below zero.
+ :negative
when "loan_payment_change"
metadata["new_payment"].to_f < metadata["previous_payment"].to_f ? :positive : :warning
when "budget_at_risk", "maintained_goal_depleted"
@@ -196,6 +202,10 @@ module InsightsHelper
end
private
+ def insight_account(insight)
+ insight.family.accounts.visible.find_by(id: (insight.metadata || {})["account_id"])
+ end
+
# "June" for month-aligned periods, "Next 30 days" / "Last 30 days" for
# rolling windows, an explicit range otherwise; subject name (account,
# merchant) for insights without a period.
diff --git a/app/jobs/generate_insights_job.rb b/app/jobs/generate_insights_job.rb
index 3a7f7f84e8..fa5d72d93f 100644
--- a/app/jobs/generate_insights_job.rb
+++ b/app/jobs/generate_insights_job.rb
@@ -147,23 +147,24 @@ class GenerateInsightsJob < ApplicationJob
elsif existing.expired?
# 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!(title: generated.title, status: "active", facts: facts,
+ # insight resurfaces, with the body filled from the current facts.
+ existing.update!(title: generated.title, body: writer.write(generated), status: "active", facts: facts,
generated_at: Time.current, read_at: nil)
existing
else
- # Same signal, same numbers: don't rewrite the body and don't undo
- # the user's read/dismissed state. Facts still
- # 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.
+ # Same signal, same numbers: don't undo the user's read/dismissed
+ # state and don't notify again. Facts still 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.
+ # The body is the template filled with those facts, so it refreshes
+ # with them; otherwise the prose keeps last week's amounts.
#
# 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)
+ existing.update!(title: generated.title, body: writer.write(generated), facts: facts, generated_at: Time.current)
nil
end
rescue ActiveRecord::RecordNotUnique
diff --git a/app/models/insight.rb b/app/models/insight.rb
index 264bb18dd5..2f8518e3a2 100644
--- a/app/models/insight.rb
+++ b/app/models/insight.rb
@@ -27,6 +27,7 @@ class Insight < ApplicationRecord
budget_at_risk
budget_on_track
maintained_goal_depleted
+ bill_not_covered
loan_payment_change
].freeze
diff --git a/app/models/insight/generator_registry.rb b/app/models/insight/generator_registry.rb
index 84fbf89a98..f13d8616a0 100644
--- a/app/models/insight/generator_registry.rb
+++ b/app/models/insight/generator_registry.rb
@@ -13,6 +13,7 @@ class Insight::GeneratorRegistry
Insight::Generators::IdleCashGenerator,
Insight::Generators::BudgetInsightGenerator,
Insight::Generators::MaintainedGoalDepletedGenerator,
+ Insight::Generators::BillNotCoveredGenerator,
Insight::Generators::LoanRepaymentChangeGenerator
].freeze
diff --git a/app/models/insight/generators/bill_not_covered_generator.rb b/app/models/insight/generators/bill_not_covered_generator.rb
new file mode 100644
index 0000000000..a5fe6641e0
--- /dev/null
+++ b/app/models/insight/generators/bill_not_covered_generator.rb
@@ -0,0 +1,180 @@
+# Checks each bill due in the next HORIZON_DAYS against the one account that
+# pays it: that account's balance today, minus the other scheduled payments
+# leaving it by the due date, plus the scheduled income and transfers
+# arriving in it by then. When what is left will not cover the bill, the
+# insight says so and by how much.
+#
+# CashFlowWarningGenerator answers a different question: whether the family's
+# combined cash dips low over 30 days, with a spending baseline on top. A
+# family can pass that check comfortably and still have rent leave an account
+# that holds only a fraction of it; this is the per-account check.
+#
+# Only Depository accounts pay bills here, and only while their balance is
+# current: a linked account's last synced balance, or a manual account with
+# recent activity. A stale balance says nothing about the due date.
+class Insight::Generators::BillNotCoveredGenerator < Insight::Generator
+ produces "bill_not_covered"
+
+ HORIZON_DAYS = 14
+ BALANCE_MAX_AGE_DAYS = 5
+
+ Flow = Data.define(:occurrence, :due_on, :amount, :bill)
+
+ def generate
+ # The bill schedule is the whole subject here, as in SubscriptionAuditGenerator:
+ # with recurring transactions off, occurrences stop being generated and
+ # what is left is a stale schedule.
+ return [] if family.recurring_transactions_disabled?
+
+ accounts = paying_accounts
+ return [] if accounts.empty?
+
+ flows = flows_by_account(accounts)
+
+ accounts.filter_map do |account|
+ first_uncovered_bill(account, flows.fetch(account.id, []))
+ end
+ end
+
+ private
+ # Bills in date order; the first the account cannot cover is reported.
+ # Later bills on the same account wait their turn, so one short account is
+ # one card rather than a card for every bill behind the first.
+ def first_uncovered_bill(account, flows)
+ flows.select(&:bill).sort_by { |flow| [ flow.due_on, flow.occurrence.id ] }.each do |bill|
+ others_by_then = flows.select { |flow| !flow.equal?(bill) && flow.due_on <= bill.due_on }
+ available = account.balance.to_d + others_by_then.sum(&:amount)
+ bill_amount = -bill.amount
+ next if available >= bill_amount
+
+ return build_bill_insight(account, bill, bill_amount, bill_amount - available)
+ end
+
+ nil
+ end
+
+ def build_bill_insight(account, bill, bill_amount, shortfall)
+ name = bill.occurrence.recurring_transaction.display_name
+
+ build_insight(
+ insight_type: "bill_not_covered",
+ priority: "high",
+ title: I18n.t("insights.titles.bill_not_covered", account: account.name, name: name),
+ template_key: "bill_not_covered",
+ facts: {
+ name: name,
+ amount: format_money(bill_amount),
+ due_on: I18n.l(bill.due_on),
+ account: account.name,
+ shortfall: format_money(shortfall)
+ },
+ # The shortfall moves with every transaction and stays a display fact:
+ # one card, and one push, per occurrence. A new due date (a snooze) is
+ # a new situation and resurfaces it.
+ metadata: {
+ account_id: account.id,
+ recurring_occurrence_id: bill.occurrence.id,
+ due_on: bill.due_on.iso8601
+ },
+ dedup_key: "bill_not_covered:#{bill.occurrence.id}"
+ )
+ end
+
+ # The insight names the account to the whole family, so only accounts
+ # every active member can see qualify. Credit cards have no balance that
+ # "covers" a charge, so they never count as the paying account. Family
+ # currency only, like the amounts the card formats.
+ def paying_accounts
+ candidates = family.accounts.visible.accessible_by_all_active_members
+ .where(accountable_type: "Depository", currency: family.currency).to_a
+ return [] if candidates.empty?
+
+ balance_dates = balance_dates_for(candidates)
+ cutoff = Date.current - BALANCE_MAX_AGE_DAYS
+
+ candidates.select do |account|
+ balance_date = balance_dates[account.id]
+ balance_date.present? && balance_date >= cutoff
+ end
+ end
+
+ # The day each balance was last known to be right. A linked account's is
+ # the date of the balance its provider last reported (the current anchor),
+ # which stops moving when syncs stop succeeding. A manual account has no
+ # provider, so its latest entry stands in: a ledger nobody touched for
+ # weeks is not a balance to promise a due date on.
+ def balance_dates_for(accounts)
+ ids = accounts.map(&:id)
+ linked_ids = Account.linked.where(id: ids).pluck(:id)
+
+ anchors = Valuation.current_anchor.joins(:entry)
+ .where(entries: { account_id: linked_ids })
+ .group("entries.account_id").maximum("entries.date")
+ activity = Entry.where(account_id: ids - linked_ids).excluding_scheduled
+ .group(:account_id).maximum(:date)
+
+ anchors.merge(activity)
+ end
+
+ # Every open occurrence that moves money in or out of a paying account
+ # before the horizon closes, as signed flows per account: negative leaves
+ # the account, positive arrives. A transfer between two paying accounts is
+ # a flow on both. Only flows in the account's own currency can be added
+ # to its balance without a rate.
+ def flows_by_account(accounts)
+ by_id = accounts.index_by(&:id)
+ occurrences = upcoming_occurrences(by_id.keys)
+ payable_ids = family.recurring_transactions.payable
+ .where(id: occurrences.map(&:recurring_transaction_id)).pluck(:id).to_set
+
+ occurrences.each_with_object(Hash.new { |hash, key| hash[key] = [] }) do |occurrence, flows|
+ series = occurrence.recurring_transaction
+ remaining = occurrence.remaining_amount
+ next unless remaining.positive?
+
+ due_today = occurrence.effective_due_on == Date.current
+
+ add = ->(account_id, amount, bill: false) do
+ account = by_id[account_id]
+ next unless account && account.currency == occurrence.currency
+ # Money due out today may already be in the balance; money due in
+ # today and still open has not been seen by the day's sync yet.
+ next if due_today && amount.negative?
+
+ flows[account_id] << Flow.new(occurrence: occurrence, due_on: occurrence.effective_due_on, amount: amount, bill: bill)
+ end
+
+ if series.amount.negative?
+ add.(series.account_id, remaining)
+ else
+ add.(series.account_id, -remaining, bill: payable_ids.include?(series.id))
+ add.(series.destination_account_id, remaining) if series.destination_account_id
+ end
+ end
+ end
+
+ # From today (see flows_by_account for what counts on the day). Past-due
+ # occurrences are left out: paid but unmatched or still to go, the balance
+ # cannot tell. A snoozed bill counts on the date it was snoozed to; an
+ # autopay bill the bank takes early is matched to its payment, and a
+ # matched occurrence is no longer open.
+ def upcoming_occurrences(account_ids)
+ RecurringOccurrence.preload_confirmed_allocated(
+ family.recurring_occurrences
+ .open_status
+ .joins(:recurring_transaction)
+ .where(recurring_transactions: { status: :active })
+ .where("recurring_transactions.account_id IN (:ids) OR recurring_transactions.destination_account_id IN (:ids)", ids: account_ids)
+ # Both endpoints every member can open, as RecurringTransaction.accessible_by
+ # requires per user: a card payment to a private card is not the
+ # family's to read, in name or in amount.
+ .where(
+ "array_remove(ARRAY[recurring_transactions.account_id, recurring_transactions.destination_account_id], NULL) <@ ARRAY(?)",
+ family.accounts.accessible_by_all_active_members.select(:id)
+ )
+ .where("#{RecurringOccurrence::EFFECTIVE_DUE_ON_SQL} BETWEEN ? AND ?", Date.current, Date.current + HORIZON_DAYS)
+ .includes(recurring_transaction: :merchant)
+ .to_a
+ )
+ end
+end
diff --git a/app/models/insight/generators/cash_flow_warning_generator.rb b/app/models/insight/generators/cash_flow_warning_generator.rb
index 64c374ed2c..10031b6a65 100644
--- a/app/models/insight/generators/cash_flow_warning_generator.rb
+++ b/app/models/insight/generators/cash_flow_warning_generator.rb
@@ -114,11 +114,7 @@ class Insight::Generators::CashFlowWarningGenerator < Insight::Generator
# remaining_amount reads the confirmed-allocation sum, and this runs
# nightly for every family: one grouped query instead of one SUM per
# occurrence in the horizon.
- sums = RecurringAllocation.confirmed
- .where(recurring_occurrence_id: occurrences.map(&:id))
- .group(:recurring_occurrence_id)
- .sum(:allocated_amount)
- occurrences.each { |occurrence| occurrence.cached_confirmed_allocated = sums.fetch(occurrence.id, 0) }
+ RecurringOccurrence.preload_confirmed_allocated(occurrences)
occurrences.map { |occurrence| Obligation.new(date: occurrence.due_on, amount: occurrence.remaining_amount) }
end
diff --git a/app/models/recurring_occurrence.rb b/app/models/recurring_occurrence.rb
index 0ae058c373..dde793d11f 100644
--- a/app/models/recurring_occurrence.rb
+++ b/app/models/recurring_occurrence.rb
@@ -126,6 +126,14 @@ class RecurringOccurrence < ApplicationRecord
# here, so row rendering issues no per-occurrence SUM.
attr_writer :cached_confirmed_allocated
+ def self.preload_confirmed_allocated(occurrences)
+ sums = RecurringAllocation.confirmed
+ .where(recurring_occurrence_id: occurrences.map(&:id))
+ .group(:recurring_occurrence_id)
+ .sum(:allocated_amount)
+ occurrences.each { |occurrence| occurrence.cached_confirmed_allocated = sums.fetch(occurrence.id, 0) }
+ end
+
def confirmed_allocated
@cached_confirmed_allocated || allocations.confirmed.sum(:allocated_amount)
end
diff --git a/config/locales/views/insights/en.yml b/config/locales/views/insights/en.yml
index 6afe0b44fd..bd3496138c 100644
--- a/config/locales/views/insights/en.yml
+++ b/config/locales/views/insights/en.yml
@@ -46,6 +46,7 @@ en:
budget_at_risk: Budget
budget_on_track: Budget
maintained_goal_depleted: Reserve
+ bill_not_covered: Bills
loan_payment_change: Loan payment
meta:
next_n_days:
@@ -67,6 +68,7 @@ en:
idle_days:
one: idle %{count} day
other: idle %{count} days
+ short_on: short on %{date}
actions:
spending_anomaly: View %{category} transactions
cash_flow_warning: Review recurring transactions
@@ -76,6 +78,7 @@ en:
idle_cash: Go to account
budget: View budget
maintained_goal_depleted: View reserve
+ bill_not_covered: Go to account
loan_payment_change: View loan
titles:
spending_anomaly:
@@ -95,6 +98,7 @@ en:
one: One category needs attention in your budget
other: "%{count} categories need attention in your budget"
budget_on_track: Your budget is on track
+ bill_not_covered: "%{account} may not cover %{name}"
loan_payment_change:
up: "%{account} payment is going up"
down: "%{account} payment is going down"
@@ -117,6 +121,7 @@ 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.
+ bill_not_covered: "%{name} of %{amount} is due on %{due_on} from %{account}. Counting the other bills and income scheduled on that account until then, it will be about %{shortfall} short."
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.yml
index 2645515b57..e245640ba1 100644
--- a/config/locales/views/insights/es.yml
+++ b/config/locales/views/insights/es.yml
@@ -46,6 +46,7 @@ es:
budget_at_risk: Presupuesto
budget_on_track: Presupuesto
maintained_goal_depleted: Reserva
+ bill_not_covered: Recibos
loan_payment_change: Cuota del préstamo
meta:
next_n_days:
@@ -67,6 +68,7 @@ es:
idle_days:
one: "%{count} día inactivo"
other: "%{count} días inactivos"
+ short_on: faltarán el %{date}
actions:
spending_anomaly: Ver transacciones de %{category}
cash_flow_warning: Revisar transacciones recurrentes
@@ -76,6 +78,7 @@ es:
idle_cash: Ir a la cuenta
budget: Ver presupuesto
maintained_goal_depleted: Ver reserva
+ bill_not_covered: Ir a la cuenta
loan_payment_change: Ver préstamo
titles:
spending_anomaly:
@@ -95,6 +98,7 @@ es:
one: Una categoría necesita atención en tu presupuesto
other: "%{count} categorías necesitan atención en tu presupuesto"
budget_on_track: Tu presupuesto va según lo previsto
+ bill_not_covered: "%{account} podría no cubrir %{name}"
loan_payment_change:
up: La cuota de %{account} va a subir
down: La cuota de %{account} va a bajar
@@ -117,6 +121,7 @@ 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.
+ bill_not_covered: "%{name}, de %{amount}, vence el %{due_on} y se paga desde %{account}. Contando los demás recibos e ingresos previstos en esa cuenta hasta entonces, faltarán unos %{shortfall}."
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/docs/llm-guides/gating-a-preview-feature.md b/docs/llm-guides/gating-a-preview-feature.md
index d2f827f61b..9e3fcaae47 100644
--- a/docs/llm-guides/gating-a-preview-feature.md
+++ b/docs/llm-guides/gating-a-preview-feature.md
@@ -142,7 +142,7 @@ The flag is per-user, not per-family. Two users in the same family can see diffe
The gate does nothing for background jobs on its own — `PreviewGateable` reads `Current.user`, which a Sidekiq worker doesn't have. A cron job runs regardless of who has preview enabled. That's usually correct: data should keep flowing, so it's there when someone opts in. `SweepExpiredGoalPledgesJob` is the typical shape — it only walks pledges that opted-in users created, so it's naturally inert for everyone else and needs no gate.
-Gate the job when it does work that isn't free. Two cases: it sends something outward (notifications, emails — gate at the send site), or it *manufactures* data for every family rather than moving existing data around, burning compute or paid API calls per family. `GenerateInsightsJob` is the second case: seven generators over the income statement and balance sheet, for every family nightly.
+Gate the job when it does work that isn't free. Two cases: it sends something outward (notifications, emails — gate at the send site), or it *manufactures* data for every family rather than moving existing data around, burning compute or paid API calls per family. `GenerateInsightsJob` is the second case: every insight generator runs over the income statement, balance sheet and bills, for every family nightly.
For a family-scoped job, roll the per-user flag up to the family:
diff --git a/test/helpers/insights_helper_test.rb b/test/helpers/insights_helper_test.rb
index 6b5a551b2d..4cb2de8ced 100644
--- a/test/helpers/insights_helper_test.rb
+++ b/test/helpers/insights_helper_test.rb
@@ -205,6 +205,21 @@ class InsightsHelperTest < ActionView::TestCase
assert_nil insight_action(dangling)
end
+ test "an uncovered bill renders destructive" do
+ assert_equal "destructive", insight_icon_color(build_insight("bill_not_covered", priority: "high"))
+ end
+
+ test "an uncovered bill leads with the shortfall and links to the paying account" do
+ account = accounts(:depository)
+ insight = build_insight("bill_not_covered",
+ metadata: { "account_id" => account.id },
+ facts: { "shortfall" => "$460.00", "due_on" => "Nov 23, 2026", "account" => "Checking Account" })
+
+ assert_equal [ "$460.00", "short on Nov 23, 2026" ], insight_key_figure(insight)
+ assert_equal account_path(account), insight_action(insight)[:href]
+ assert_equal "Bills · Checking Account", insight_meta_line(insight)
+ end
+
test "maintained reserve metadata and action render in German" do
family = families(:dylan_family)
goal = family.goals.first
diff --git a/test/jobs/generate_insights_job_test.rb b/test/jobs/generate_insights_job_test.rb
index 6bc16e3249..96f188d9a2 100644
--- a/test/jobs/generate_insights_job_test.rb
+++ b/test/jobs/generate_insights_job_test.rb
@@ -162,7 +162,9 @@ class GenerateInsightsJobTest < ActiveJob::TestCase
assert_equal original_body, insight.reload.body
end
- test "persists display facts and refreshes them without a body rewrite when metadata is unchanged" do
+ # The body is the i18n template filled with the facts, so it refreshes with
+ # them; an unchanged metadata still means no resurfacing and no new push.
+ test "refreshes display facts and the body in place when metadata is unchanged" do
stub_generated([ generated_insight ])
GenerateInsightsJob.perform_now(family_id: @family.id)
@@ -176,10 +178,33 @@ class GenerateInsightsJobTest < ActiveJob::TestCase
insight.reload
assert_equal "$5040", insight.facts["balance"]
- assert_equal original_body, insight.body
+ assert_not_equal original_body, insight.body
+ assert_includes insight.body, "$5040"
assert insight.read?
end
+ test "a body refreshed in place is not notified again" do
+ stub_generated([ generated_insight(priority: "high") ])
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+
+ DeliverInsightNotificationJob.expects(:enqueue_for).never
+ stub_generated([ generated_insight(priority: "high", display_balance: 5040) ])
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ end
+
+ test "an expired insight that returns with new display facts gets a fresh body" 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")
+
+ stub_generated([], succeeded_types: [ "idle_cash" ])
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ stub_generated([ generated_insight(display_balance: 5040) ])
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+
+ assert_includes insight.reload.body, "$5040"
+ 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.
diff --git a/test/models/insight/body_writer_test.rb b/test/models/insight/body_writer_test.rb
index ba67c3be3c..ab311e18f0 100644
--- a/test/models/insight/body_writer_test.rb
+++ b/test/models/insight/body_writer_test.rb
@@ -45,6 +45,13 @@ class Insight::BodyWriterTest < ActiveSupport::TestCase
end
end
+ test "uncovered bills have Spanish copy of their own" do
+ TEMPLATE_FACTS.slice("bill_not_covered").each do |template_key, facts|
+ assert I18n.exists?("insights.templates.#{template_key}", :es, fallback: false), "missing es copy for #{template_key}"
+ assert I18n.t!("insights.templates.#{template_key}", locale: :es, **facts).present?
+ end
+ end
+
private
# One representative facts hash per template a generator can emit. Keeps
# the i18n templates honest: a renamed key or interpolation raises here
@@ -62,7 +69,8 @@ class Insight::BodyWriterTest < ActiveSupport::TestCase
"idle_cash" => { account: "Emergency fund", balance: "$28,400.00", idle_days: 60 },
"budget_at_risk.over" => { categories: "Food & Drink and Travel", count: 2, budget_spent_pct: 84 },
"budget_at_risk.near" => { categories: "Shopping", count: 1, budget_spent_pct: 72 },
- "budget_on_track" => { spent: "$2,948.00", budgeted: "$5,200.00", budget_spent_pct: 57 }
+ "budget_on_track" => { spent: "$2,948.00", budgeted: "$5,200.00", budget_spent_pct: 57 },
+ "bill_not_covered" => { name: "Rent", amount: "$1,460.00", due_on: "Dec 7, 2026", account: "Joint account", shortfall: "$300.00" }
}.freeze
def placeholders(text)
diff --git a/test/models/insight/generators/bill_not_covered_generator_test.rb b/test/models/insight/generators/bill_not_covered_generator_test.rb
new file mode 100644
index 0000000000..c5468636ab
--- /dev/null
+++ b/test/models/insight/generators/bill_not_covered_generator_test.rb
@@ -0,0 +1,254 @@
+require "test_helper"
+
+class Insight::Generators::BillNotCoveredGeneratorTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ travel_to Date.new(2026, 11, 16)
+
+ @family = families(:dylan_family)
+ # Manual Depository account shared with family_member. Its balance counts
+ # as current because it had activity yesterday.
+ @checking = accounts(:depository)
+ Entry.where(account: @checking).delete_all
+ create_transaction(account: @checking, amount: 10, date: 1.day.ago.to_date)
+ @checking.update_columns(balance: 1000)
+ end
+
+ test "flags a bill the paying account will not cover on its due date" do
+ rent = scheduled("Rent", 1460, 7.days.from_now)
+
+ insight = only_insight
+
+ assert_equal "bill_not_covered", insight.insight_type
+ assert_equal "high", insight.priority
+ assert_equal "bill_not_covered:#{rent.id}", insight.dedup_key
+ assert_equal @checking.id, insight.metadata[:account_id]
+ assert_equal rent.id, insight.metadata[:recurring_occurrence_id]
+ assert_equal "$460.00", insight.facts[:shortfall]
+ assert_equal "Checking Account may not cover Rent", insight.title
+ assert_equal "Rent of $1,460.00 is due on #{I18n.l(rent.due_on)} from Checking Account. " \
+ "Counting the other bills and income scheduled on that account until then, it will be about $460.00 short.",
+ Insight::BodyWriter.new.write(insight)
+ end
+
+ test "stays quiet when the balance covers the bill" do
+ @checking.update_columns(balance: 1460)
+ scheduled("Rent", 1460, 7.days.from_now)
+
+ assert_empty generate
+ end
+
+ test "scheduled income into the account before the due date covers the bill" do
+ scheduled("Rent", 1460, 7.days.from_now)
+ scheduled("Salary", -800, 3.days.from_now)
+
+ assert_empty generate
+ end
+
+ test "a scheduled transfer into the account before the due date covers the bill" do
+ savings = accounts(:connected)
+ AccountShare.create!(account: savings, user: users(:family_member), permission: :read_only)
+ scheduled("Rent", 1460, 7.days.from_now)
+ scheduled("Top up", 500, 2.days.from_now, account: savings, destination: @checking)
+
+ assert_empty generate
+ end
+
+ # The same rule as RecurringTransaction.accessible_by: a series with an
+ # endpoint some member cannot open is not theirs to see, in name or amount.
+ test "a payment to an account private to one member is not reported" do
+ account_shares(:credit_card_shared_with_member).destroy!
+ scheduled("Payment to private card", 1460, 7.days.from_now, destination: accounts(:credit_card))
+
+ assert_empty generate
+
+ users(:family_member).update_columns(active: false)
+ assert_equal 1, generate.size, "with only the owner active, the card payment is everyone's"
+ end
+
+ test "a transfer in from an account private to one member is not counted" do
+ rent = scheduled("Rent", 1460, 7.days.from_now)
+ scheduled("Top up from private savings", 500, 2.days.from_now, account: accounts(:connected), destination: @checking)
+
+ assert_equal rent.id, only_insight.metadata[:recurring_occurrence_id]
+ end
+
+ test "nothing is generated when the family turned recurring transactions off" do
+ scheduled("Rent", 1460, 7.days.from_now)
+ @family.update!(recurring_transactions_disabled: true)
+
+ assert_empty generate
+ end
+
+ test "income due today that has not arrived yet counts" do
+ scheduled("Rent", 1460, 3.days.from_now)
+ scheduled("Salary", -800, Date.current)
+
+ assert_empty generate
+ end
+
+ test "income and the bill on the same day count together" do
+ scheduled("Rent", 1460, 3.days.from_now)
+ scheduled("Salary", -800, 3.days.from_now)
+
+ assert_empty generate
+ end
+
+ test "a payment due today is not counted again: it may already be in the balance" do
+ @checking.update_columns(balance: 1500)
+ scheduled("Phone", 600, Date.current)
+ scheduled("Rent", 1460, 3.days.from_now)
+
+ assert_empty generate
+ end
+
+ test "a card payment from checking is a bill" do
+ payment = scheduled("Card payment", 1460, 7.days.from_now, destination: accounts(:credit_card))
+
+ assert_equal payment.id, only_insight.metadata[:recurring_occurrence_id]
+ end
+
+ test "an occurrence in another currency is skipped" do
+ rent = scheduled("Rent", 1460, 7.days.from_now)
+ rent.update!(currency: "EUR")
+
+ assert_empty generate
+ end
+
+ test "the material metadata does not move with the shortfall, so it is one push per occurrence" do
+ rent = scheduled("Rent", 1460, 7.days.from_now)
+ before = only_insight
+
+ @checking.update_columns(balance: 600)
+ after = only_insight
+
+ assert_equal({ account_id: @checking.id, recurring_occurrence_id: rent.id, due_on: rent.due_on.iso8601 }, after.metadata)
+ assert_equal before.metadata, after.metadata
+ assert_equal "$860.00", after.facts[:shortfall]
+ end
+
+ test "an account in another currency than the family's is left out" do
+ @checking.update_columns(currency: "EUR")
+ scheduled("Rent", 1460, 7.days.from_now, currency: "EUR")
+
+ assert_empty generate
+ end
+
+ test "income that arrives after the due date does not count" do
+ scheduled("Rent", 1460, 7.days.from_now)
+ scheduled("Salary", -800, 9.days.from_now)
+
+ assert_equal "$460.00", only_insight.facts[:shortfall]
+ end
+
+ test "another outflow from the same account before the due date uncovers the bill" do
+ @checking.update_columns(balance: 2000)
+ scheduled("Phone", 600, 2.days.from_now)
+ rent = scheduled("Rent", 1460, 7.days.from_now)
+
+ insight = only_insight
+
+ assert_equal rent.id, insight.metadata[:recurring_occurrence_id]
+ assert_equal "$60.00", insight.facts[:shortfall]
+ end
+
+ test "outflows from other accounts do not count against this one" do
+ @checking.update_columns(balance: 1500)
+ scheduled("Rent", 1460, 7.days.from_now)
+ scheduled("Phone", 600, 2.days.from_now, account: accounts(:connected))
+
+ assert_empty generate
+ end
+
+ test "only what is still owed on a partly paid bill counts" do
+ rent = scheduled("Rent", 1460, 7.days.from_now)
+ RecurringAllocation.create!(
+ recurring_occurrence: rent, state: :confirmed, source: :user_confirmed,
+ allocated_amount: 500, currency: "USD", paid_on: Date.current
+ )
+
+ assert_empty generate
+ end
+
+ test "only the first uncovered bill on an account is reported" do
+ first = scheduled("Rent", 1460, 5.days.from_now)
+ scheduled("Insurance", 300, 9.days.from_now)
+
+ assert_equal first.id, only_insight.metadata[:recurring_occurrence_id]
+ end
+
+ test "bills beyond the horizon are not checked" do
+ scheduled("Rent", 1460, (Insight::Generators::BillNotCoveredGenerator::HORIZON_DAYS + 1).days.from_now)
+
+ assert_empty generate
+ end
+
+ test "a manual account without recent activity has no balance to trust" do
+ Entry.where(account: @checking).delete_all
+ create_transaction(account: @checking, amount: 10, date: 20.days.ago.to_date)
+ scheduled("Rent", 1460, 7.days.from_now)
+
+ assert_empty generate
+ end
+
+ test "a linked account counts only while its synced balance is recent" do
+ connected = accounts(:connected)
+ AccountShare.create!(account: connected, user: users(:family_member), permission: :full_control)
+ Entry.where(account: connected).delete_all
+ anchor = create_valuation(account: connected, kind: "current_anchor", amount: 1000, date: 10.days.ago.to_date)
+ connected.update_columns(balance: 1000)
+ scheduled("Rent", 1460, 7.days.from_now, account: connected)
+
+ assert_empty generate, "a balance last synced ten days ago is stale"
+
+ anchor.update!(date: 1.day.ago.to_date)
+ assert_equal connected.id, only_insight.metadata[:account_id]
+ end
+
+ test "a credit card is not treated as a paying account" do
+ card = accounts(:credit_card)
+ create_transaction(account: card, amount: 10, date: 1.day.ago.to_date)
+ scheduled("Streaming", 5000, 7.days.from_now, account: card)
+
+ assert_empty generate
+ end
+
+ test "an account private to one member is left out of the shared feed" do
+ connected = accounts(:connected)
+ Entry.where(account: connected).delete_all
+ create_valuation(account: connected, kind: "current_anchor", amount: 1000, date: Date.current)
+ connected.update_columns(balance: 1000)
+ scheduled("Rent", 1460, 7.days.from_now, account: connected)
+
+ assert_empty generate
+
+ users(:family_member).update_columns(active: false)
+ assert_equal connected.id, only_insight.metadata[:account_id], "an inactive member does not hide an account"
+ end
+
+ private
+ def generate
+ Insight::Generators::BillNotCoveredGenerator.new(@family).generate
+ end
+
+ def only_insight
+ insights = generate
+ assert_equal 1, insights.size, "expected exactly one insight, got #{insights.map(&:dedup_key)}"
+ insights.first
+ end
+
+ # One active series with exactly one open occurrence on `due`. Positive
+ # amounts leave `account`, negative ones arrive in it; a destination makes
+ # it a transfer into that account.
+ def scheduled(name, amount, due, account: @checking, destination: nil, currency: "USD")
+ due = due.to_date
+ series = @family.recurring_transactions.create!(
+ name: name, account: account, destination_account: destination, amount: amount, currency: currency,
+ expected_day_of_month: due.day, last_occurrence_date: due << 1, next_expected_date: due,
+ status: "active", manual: true
+ )
+ series.recurring_occurrences.delete_all
+ series.recurring_occurrences.create!(family: @family, original_due_on: due, due_on: due, currency: currency)
+ end
+end