The personal finance app for everyone (by everyone)
Ruby
feat(insights): proactive financial intelligence feed (#2550)
Juan José Mata66cf9e7f0b0e
diff --git a/app/components/DS/button.rb b/app/components/DS/button.rbindex 6abe4cc089..67c33ecb59 100644--- a/app/components/DS/button.rb+++ b/app/components/DS/button.rb@@ -43,6 +43,16 @@ class DS::Button < DS::Buttonishmerged_opts[:type] ||= "button"end+ # A bare `aria_label:` option reaches the tag helpers as a literal+ # `aria_label` attribute — Rails only dasherizes the nested `aria:` hash.+ # Callers use both spellings, so fold `aria_label:` into the aria hash+ # (before the icon fallback below, which must see it as a real label).+ if (aria_label = merged_opts.delete(:aria_label)).present?+ aria = (merged_opts[:aria] || {}).symbolize_keys+ aria[:label] = aria_label if aria[:label].blank?+ merged_opts[:aria] = aria+ end+# Icon-only buttons have no visible text node, so screen readers fall# back to announcing "button" with no name. Derive a humanized fallback# from the icon key so AT users hear *something* meaningful; explicitdiff --git a/app/components/DS/empty_state.rb b/app/components/DS/empty_state.rbindex 937954d91e..db4f8daa0b 100644--- a/app/components/DS/empty_state.rb+++ b/app/components/DS/empty_state.rb@@ -10,11 +10,12 @@ class DS::EmptyState < DesignSystemComponent# <% end %>renders_one :action- def initialize(icon:, title:, description: nil, icon_size: "xl", **opts)+ def initialize(icon:, title:, description: nil, icon_size: "xl", icon_custom: false, **opts)@icon = icon@title = title@description = description@icon_size = icon_size+ @icon_custom = icon_custom@opts = optsend@@ -22,7 +23,7 @@ class DS::EmptyState < DesignSystemComponent<%= content_tag :div,class: class_names("flex flex-col items-center text-center px-4 py-12", @opts[:class]),**@opts.except(:class) do %>- <div class="mb-4"><%= helpers.icon(@icon, size: @icon_size) %></div>+ <div class="mb-4"><%= helpers.icon(@icon, size: @icon_size, custom: @icon_custom) %></div><p class="text-primary font-medium mb-2"><%= @title %></p><% if @description.present? %><p class="<%= class_names("text-secondary text-sm max-w-md", ("mb-4" if action?)) %>"><%= @description %></p>diff --git a/app/controllers/insights_controller.rb b/app/controllers/insights_controller.rbnew file mode 100644index 0000000000..7f339e0fbf--- /dev/null+++ b/app/controllers/insights_controller.rb@@ -0,0 +1,62 @@+class InsightsController < ApplicationController+ before_action :set_insight, only: %i[dismiss undismiss]++ def index+ load_feed+ @breadcrumbs = [ [ t("breadcrumbs.home"), root_path ], [ t("insights.index.title"), nil ] ]++ # Viewing the feed is what "read" means here; the New badge for this+ # render comes from @unread_ids captured above. Turbo's hover prefetch+ # hits this GET before the user actually navigates, so skip the write+ # for prefetch requests or badges would clear on hover.+ unless prefetch_request?+ Current.family.insights.active.update_all(status: "read", read_at: Time.current, updated_at: Time.current)+ end+ end++ def dismiss+ @insight.dismiss!++ respond_to do |format|+ format.turbo_stream+ format.html { redirect_back_or_to insights_path }+ end+ end++ def undismiss+ @insight.undismiss!+ load_feed++ respond_to do |format|+ format.turbo_stream+ format.html { redirect_back_or_to insights_path }+ end+ end++ def refresh+ GenerateInsightsJob.perform_later(family_id: Current.family.id)++ respond_to do |format|+ # Swaps the button into its pending state; the job broadcasts the+ # refreshed list and the idle button back when it finishes.+ format.turbo_stream+ format.html { redirect_to insights_path, notice: t("insights.refresh.queued") }+ end+ end++ private+ def set_insight+ @insight = Current.family.insights.find(params[:id])+ end++ def load_feed+ @insights = Current.family.insights.visible.ordered.to_a+ @unread_ids = @insights.select(&:active?).map(&:id).to_set+ end++ # Turbo sends X-Sec-Purpose (the fetch spec forbids setting Sec-Purpose+ # from JS) on hover-prefetch requests.+ def prefetch_request?+ request.headers["X-Sec-Purpose"] == "prefetch" || request.headers["Sec-Purpose"].to_s.include?("prefetch")+ end+enddiff --git a/app/controllers/pages_controller.rb b/app/controllers/pages_controller.rbindex 844b5e0666..e157dbba86 100644--- a/app/controllers/pages_controller.rb+++ b/app/controllers/pages_controller.rb@@ -8,6 +8,11 @@ class PagesController < ApplicationController# false for content-sized widgets (tables, stat grids)# min_height: floor in pxDASHBOARD_SECTION_LAYOUTS = {+ # Width-toggleable but full by default: the feed is much shorter than any+ # other single-width widget, so defaulting to half leaves a grid hole the+ # masonry can't backfill (dense placement needs a later card short enough+ # to fit beside it, and none is). Users who pair it manually can go half.+ "insights_feed" => { col_span: "full", grow: false, min_height: 0, width_toggle: true },"cashflow_sankey" => { col_span: "full", grow: false, min_height: 384, width_toggle: true },"outflows_donut" => { col_span: "single", grow: false, min_height: 0 },"investment_summary" => { col_span: "single", grow: false, min_height: 0, width_toggle: true },@@ -41,6 +46,7 @@ class PagesController < ApplicationController@cashflow_sankey_data = build_cashflow_sankey_data(net_totals, income_totals, expense_totals, family_currency)@outflows_data = build_outflows_donut_data(net_totals)+ @feed_insights = Current.family.insights.visible.ordered.limit(3)@dashboard_sections = build_dashboard_sections@@ -104,6 +110,15 @@ class PagesController < ApplicationControllerdef build_dashboard_sectionsall_sections = [+ {+ key: "insights_feed",+ title: "pages.dashboard.insights_feed.title",+ partial: "pages/dashboard/insights_feed",+ layout: section_layout("insights_feed"),+ locals: { insights: @feed_insights },+ visible: @feed_insights.any?,+ collapsible: true+ },{key: "cashflow_sankey",title: "pages.dashboard.cashflow_sankey.title",@@ -157,9 +172,18 @@ class PagesController < ApplicationControllerall_sections.find { |s| s[:key] == key }end.compact- # Add any new sections that aren't in the saved order (future-proofing)+ # Add any new sections that aren't in the saved order (future-proofing).+ # The insights feed leads instead of appending: it's a proactive surface,+ # and appending would bury it below the fold for every family with a+ # saved order. Users can still drag it back down — that choice persists.all_sections.each do |section|- ordered_sections << section unless ordered_sections.include?(section)+ next if ordered_sections.include?(section)++ if section[:key] == "insights_feed"+ ordered_sections.unshift(section)+ else+ ordered_sections << section+ endendordered_sectionsdiff --git a/app/helpers/insights_helper.rb b/app/helpers/insights_helper.rbnew file mode 100644index 0000000000..6ee5ca3391--- /dev/null+++ b/app/helpers/insights_helper.rb@@ -0,0 +1,158 @@+module InsightsHelper+ INSIGHT_ICONS = {+ "spending_anomaly" => "activity",+ "cash_flow_warning" => "alert-triangle",+ "net_worth_milestone" => "trophy",+ "subscription_audit" => "repeat",+ "savings_rate_change" => "piggy-bank",+ "idle_cash" => "wallet",+ "budget_at_risk" => "alert-triangle",+ "budget_on_track" => "circle-check"+ }.freeze++ def insight_icon_key(insight)+ INSIGHT_ICONS.fetch(insight.insight_type, "lightbulb")+ end++ # "Savings rate · June" / "Cash flow · Next 30 days" — the card's meta line.+ # Uses the insight's stored period; falls back to the subject (account or+ # merchant name from facts) for insights without one.+ def insight_meta_line(insight)+ parts = [ t("insights.types.#{insight.insight_type}", default: insight.insight_type.humanize) ]+ parts << insight_period_label(insight)+ parts.compact.join(" · ")+ end++ # [value, caption] for the card's right-aligned key figure, from the display+ # facts stored on the row. Nil (no figure) for rows written before facts+ # were persisted — they backfill on the next nightly run.+ def insight_key_figure(insight)+ facts = insight.facts || {}+ return nil if facts.blank?++ case insight.insight_type+ when "savings_rate_change"+ return nil unless facts["change_pp"]+ sign = insight_sentiment(insight) == :positive ? "+" : "−"+ [ "#{sign}#{facts["change_pp"]} pp", t("insights.figures.vs_previous") ]+ when "net_worth_milestone"+ facts["net_worth"] && [ facts["net_worth"], t("insights.figures.today") ]+ when "spending_anomaly"+ facts["projected_spend"] && [ facts["projected_spend"], t("insights.figures.on_pace") ]+ when "cash_flow_warning"+ facts["projected_low"] && [ facts["projected_low"], facts["projected_low_date"] ]+ when "subscription_audit"+ facts["amount"] && [ facts["amount"], t("insights.figures.days_overdue", count: facts["days_overdue"].to_i) ]+ when "idle_cash"+ facts["balance"] && [ facts["balance"], t("insights.figures.idle_days", count: facts["idle_days"].to_i) ]+ when "budget_at_risk", "budget_on_track"+ facts["budget_spent_pct"] && [ "#{facts["budget_spent_pct"]}%", t("insights.figures.of_budget") ]+ end+ end++ # The contextual action for a card, built from the subject ids each+ # generator stores in metadata. Returns nil when the subject no longer+ # resolves (deleted category/account) — the card renders without a link.+ # Looks up through insight.family, not Current, so broadcast renders work.+ def insight_action(insight)+ metadata = insight.metadata || {}++ case insight.insight_type+ when "spending_anomaly"+ category = insight.family.categories.find_by(id: metadata["category_id"])+ category && {+ text: t("insights.actions.spending_anomaly", category: category.name),+ href: transactions_path(q: { categories: [ category.name ] })+ }+ when "idle_cash"+ account = insight.family.accounts.visible.find_by(id: metadata["account_id"])+ account && { text: t("insights.actions.idle_cash"), href: account_path(account) }+ when "subscription_audit"+ { text: t("insights.actions.subscription_audit"), href: recurring_transactions_path }+ when "cash_flow_warning"+ { text: t("insights.actions.cash_flow_warning"), href: recurring_transactions_path }+ when "savings_rate_change"+ return nil unless insight.period_start && insight.period_end+ { text: t("insights.actions.savings_rate_change"),+ href: transactions_path(q: { start_date: insight.period_start.to_s, end_date: insight.period_end.to_s }) }+ when "net_worth_milestone"+ { text: t("insights.actions.net_worth_milestone"), href: reports_path }+ when "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)) }+ end+ end++ # Sentiment picks the color; priority only orders the feed. The two are+ # orthogonal — a big savings-rate improvement is high priority AND good news,+ # and must not render red. Red is reserved for a projected-negative balance,+ # matching the app's wider rule that even negative amounts aren't red.+ def insight_icon_color(insight)+ case insight_sentiment(insight)+ when :positive then "success"+ when :negative then "destructive"+ when :warning then "warning"+ else "default"+ end+ end++ # CSS color for the tinted icon circle (FilledIcon-style, color-mix'd to a+ # 10% tint) — CSS variables so dark mode retunes automatically.+ def insight_icon_css_color(insight)+ case insight_sentiment(insight)+ when :positive then "var(--color-success)"+ when :negative then "var(--color-destructive)"+ when :warning then "var(--color-warning)"+ else "var(--color-gray-500)"+ end+ end++ # Derived from type + the direction already stored in metadata, so rows+ # written before a metadata-shape change degrade to :warning, never :negative.+ def insight_sentiment(insight)+ metadata = insight.metadata || {}++ case insight.insight_type+ when "net_worth_milestone", "budget_on_track"+ :positive+ when "savings_rate_change"+ metadata["current_rate"].to_f >= metadata["previous_rate"].to_f ? :positive : :warning+ when "spending_anomaly"+ metadata["direction"] == "below" ? :positive : :warning+ when "cash_flow_warning"+ metadata["negative"] ? :negative : :warning+ when "budget_at_risk"+ :warning+ else+ :neutral+ end+ end++ private+ # "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.+ def insight_period_label(insight)+ start_date = insight.period_start+ end_date = insight.period_end++ if start_date.nil? || end_date.nil?+ facts = insight.facts || {}+ return facts["account"] || facts["name"]+ end++ if start_date == start_date.beginning_of_month && end_date == start_date.end_of_month+ format = start_date.year == Date.current.year ? "%B" : "%B %Y"+ return I18n.l(start_date, format: format)+ end++ days = (end_date - start_date).to_i+ if start_date >= Date.current - 1+ t("insights.meta.next_n_days", count: days)+ elsif end_date >= Date.current - 1+ t("insights.meta.last_n_days", count: days)+ else+ t("insights.meta.date_range", from: I18n.l(start_date, format: :short), to: I18n.l(end_date, format: :short))+ end+ end+enddiff --git a/app/jobs/generate_insights_job.rb b/app/jobs/generate_insights_job.rbnew file mode 100644index 0000000000..4155764b1d--- /dev/null+++ b/app/jobs/generate_insights_job.rb@@ -0,0 +1,173 @@+class GenerateInsightsJob < ApplicationJob+ queue_as :scheduled+ sidekiq_options lock: :until_executed, on_conflict: :log++ # Without args (cron): fans out one job per family.+ # With family_id: generates and upserts that family's insights.+ def perform(family_id: nil)+ if family_id.present?+ generate_for_family(family_id)+ else+ fan_out+ end+ end++ private+ def fan_out+ Family.find_each do |family|+ GenerateInsightsJob.perform_later(family_id: family.id)+ rescue => e+ Rails.logger.error("Failed to enqueue insight generation for family #{family.id}: #{e.message}")+ end+ end++ def generate_for_family(family_id)+ family = Family.find_by(id: family_id)+ return unless family+ return if family.accounts.none?++ with_advisory_lock(family_id) do+ I18n.with_locale(family.locale) do+ result = Insight::GeneratorRegistry.new(family).generate_all+ upsert_insights(family, result.insights)+ expire_stale_insights(family, result)+ end+ end++ # Outside the lock on purpose: even a lock-skipped run re-broadcasts the+ # current state, so a subscribed /insights page (waiting on its manual+ # refresh) always gets its list and button restored.+ broadcast_feed(family)+ end++ def broadcast_feed(family)+ insights = family.insights.visible.ordered.to_a+ unread_ids = insights.select(&:active?).map(&:id).to_set++ Turbo::StreamsChannel.broadcast_replace_to(+ [ family, :insights ],+ target: "insights-list",+ partial: "insights/list",+ locals: { insights: insights, unread_ids: unread_ids }+ )+ Turbo::StreamsChannel.broadcast_replace_to(+ [ family, :insights ],+ target: "insights-refresh",+ partial: "insights/refresh_button",+ locals: { pending: false }+ )+ end++ # A visible insight whose generator ran successfully but did not re-emit+ # its dedup_key has had its condition clear — hide it. Types whose+ # generator crashed are left untouched so a transient failure can't wipe+ # out healthy insights.+ def expire_stale_insights(family, result)+ family.insights+ .visible+ .where(insight_type: result.succeeded_types)+ .where.not(dedup_key: result.insights.map(&:dedup_key))+ .update_all(status: "expired", updated_at: Time.current)+ end++ def upsert_insights(family, generated_insights)+ writer = Insight::BodyWriter.new(family)++ generated_insights.each do |generated|+ metadata = normalize_json(generated.metadata)+ facts = normalize_json(generated.facts)+ existing = family.insights.find_by(dedup_key: generated.dedup_key)++ if existing.nil?+ family.insights.create!(+ insight_type: generated.insight_type,+ priority: generated.priority,+ status: "active",+ title: generated.title,+ body: writer.write(generated),+ metadata: metadata,+ facts: facts,+ currency: generated.currency,+ period_start: generated.period_start,+ period_end: generated.period_end,+ generated_at: Time.current,+ dedup_key: generated.dedup_key+ )+ elsif existing.metadata != metadata+ # The numbers changed materially: refresh the prose and resurface the+ # insight even if the user had read or dismissed the stale version.+ existing.update!(+ priority: generated.priority,+ status: "active",+ title: generated.title,+ body: writer.write(generated),+ metadata: metadata,+ facts: facts,+ period_start: generated.period_start,+ period_end: generated.period_end,+ generated_at: Time.current,+ read_at: nil,+ dismissed_at: nil+ )+ 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!(status: "active", facts: facts, generated_at: Time.current, read_at: nil)+ else+ # Same signal, same numbers: don't rewrite the body (avoids an LLM+ # call) 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.+ existing.update!(facts: facts, generated_at: Time.current)+ end+ rescue ActiveRecord::RecordNotUnique+ # A concurrent run created the same dedup_key first; it owns this row.+ next+ rescue => e+ DebugLogEntry.capture(+ category: "insights",+ level: "error",+ message: "Failed to upsert insight #{generated.dedup_key}: #{e.class}: #{e.message}",+ source: "GenerateInsightsJob",+ family: family,+ metadata: { dedup_key: generated.dedup_key, insight_type: generated.insight_type }+ )+ end+ end++ # GeneratedInsight metadata/facts may hold symbols, dates, or BigDecimals;+ # the persisted jsonb columns round-trip everything to JSON primitives.+ # Compare like with like or every nightly run would look like a material+ # change.+ def normalize_json(hash)+ JSON.parse(hash.to_json)+ end++ def with_advisory_lock(family_id)+ lock_key = advisory_lock_key(family_id)+ acquired = ActiveRecord::Base.connection.select_value(+ ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_try_advisory_lock(?)", lock_key ])+ )++ unless acquired+ Rails.logger.warn("Skipped insight generation for family #{family_id}: advisory lock unavailable")+ return+ end++ begin+ yield+ ensure+ ActiveRecord::Base.connection.execute(+ ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_advisory_unlock(?)", lock_key ])+ )+ end+ end++ def advisory_lock_key(family_id)+ # Use (nearly) the full signed-bigint space pg_try_advisory_lock accepts+ # to keep the collision odds between families negligible.+ Digest::MD5.hexdigest("generate_insights:#{family_id}").to_i(16) % (2**62)+ end+enddiff --git a/app/models/family.rb b/app/models/family.rbindex afa6d40122..45324932ab 100644--- a/app/models/family.rb+++ b/app/models/family.rb@@ -113,6 +113,7 @@ class Family < ApplicationRecordhas_many :llm_usages, dependent: :destroyhas_many :recurring_transactions, dependent: :destroy+ has_many :insights, dependent: :destroyvalidates :locale, inclusion: { in: I18n.available_locales.map(&:to_s) }validates :date_format, inclusion: { in: DATE_FORMATS.map(&:last) }diff --git a/app/models/insight.rb b/app/models/insight.rbnew file mode 100644index 0000000000..02d562c4d4--- /dev/null+++ b/app/models/insight.rb@@ -0,0 +1,54 @@+# A proactive, typed observation about a family's finances, produced nightly+# by GenerateInsightsJob. The financial logic lives in Insight::Generators::*;+# the LLM (when configured) only writes the `body` prose from pre-computed+# numbers, so rows are safe to render verbatim.+#+# Status semantics: `read` and `dismissed` are user actions; `expired` is the+# system's — set when a signal stops being generated (the condition cleared).+# A returning condition reactivates an expired row but never a dismissed one.+class Insight < ApplicationRecord+ belongs_to :family++ TYPES = %w[+ spending_anomaly+ cash_flow_warning+ net_worth_milestone+ subscription_audit+ savings_rate_change+ idle_cash+ budget_at_risk+ budget_on_track+ ].freeze++ enum :status, { active: "active", read: "read", dismissed: "dismissed", expired: "expired" }+ enum :priority, { high: "high", medium: "medium", low: "low" }, prefix: true++ validates :insight_type, presence: true, inclusion: { in: TYPES }+ validates :title, :body, :dedup_key, presence: true+ # Mirrors the DB unique index so direct callers get a validation error+ # instead of ActiveRecord::RecordNotUnique; races still hit the index.+ validates :dedup_key, uniqueness: { scope: :family_id }++ # Everything the user hasn't dismissed; what the feed renders.+ scope :visible, -> { where(status: [ :active, :read ]) }+ scope :ordered, -> {+ order(Arel.sql("CASE insights.priority WHEN 'high' THEN 0 WHEN 'medium' THEN 1 ELSE 2 END"))+ .order(generated_at: :desc)+ }++ def mark_read!+ return unless active?++ update!(status: :read, read_at: Time.current)+ end++ def dismiss!+ update!(status: :dismissed, dismissed_at: Time.current)+ end++ # Undoes a dismissal without re-badging the insight as new — the user has+ # obviously seen it, so it returns as read.+ def undismiss!+ update!(status: :read, dismissed_at: nil, read_at: read_at || Time.current)+ end+enddiff --git a/app/models/insight/body_writer.rb b/app/models/insight/body_writer.rbnew file mode 100644index 0000000000..76587af4b3--- /dev/null+++ b/app/models/insight/body_writer.rb@@ -0,0 +1,75 @@+# Writes the user-facing prose for a GeneratedInsight. The LLM acts as a+# writer, not a reasoner: it receives pre-computed facts and may only phrase+# them. When no LLM provider is configured (common on self-hosted installs),+# nobody in the family has opted into AI, or the call fails, the i18n template+# interpolated with the same facts is used instead, so insight generation+# never depends on an external service.+class Insight::BodyWriter+ SYSTEM_PROMPT = <<~PROMPT.freeze+ You write short insights for a personal finance app.+ Rules:+ - Write 1-2 plain sentences addressed to the user as "you".+ - Use only the facts provided. Never invent numbers, dates, or projections.+ - Repeat monetary amounts exactly as formatted in the facts.+ - No financial advice, no jargon, no emoji, no exclamation marks, no lists or headers.+ - Respond with the sentences only.+ PROMPT++ def initialize(family)+ @family = family+ end++ def write(generated_insight)+ llm_body(generated_insight) || template_body(generated_insight)+ end++ private+ attr_reader :family++ def template_body(generated_insight)+ I18n.t(+ "insights.templates.#{generated_insight.template_key}",+ **generated_insight.facts.symbolize_keys+ )+ end++ def llm_body(generated_insight)+ return nil unless provider++ prompt = <<~PROMPT+ Insight type: #{generated_insight.insight_type.humanize}+ Facts: #{generated_insight.facts.to_json}+ PROMPT++ response = provider.chat_response(+ prompt,+ model: provider.class.effective_model,+ instructions: SYSTEM_PROMPT,+ family: family+ )+ return nil unless response.success?++ response.data.messages.filter_map(&:output_text).join(" ").strip.presence+ rescue => e+ DebugLogEntry.capture(+ category: "insights",+ level: "warn",+ message: "Insight::BodyWriter narration failed: #{e.class}: #{e.message}",+ source: "Insight::BodyWriter",+ family: family,+ metadata: { insight_type: generated_insight.insight_type }+ )+ nil+ end++ # This job runs unprompted for every family, so unlike chat (where the user+ # initiates each call) LLM narration is gated on someone in the family+ # having AI enabled — consent to share financial data with the provider,+ # and a cost cap in managed mode. Everyone else gets the template body.+ def provider+ return @provider if defined?(@provider)+ return @provider = nil unless family.users.any?(&:ai_enabled?)++ @provider = Provider::Registry.preferred_llm_provider+ end+enddiff --git a/app/models/insight/generator.rb b/app/models/insight/generator.rbnew file mode 100644index 0000000000..d426f434bc--- /dev/null+++ b/app/models/insight/generator.rb@@ -0,0 +1,93 @@+# Base class for insight generators. Subclasses compute a financial signal in+# pure Ruby and return GeneratedInsight records — numbers only, no prose. The+# prose (`body`) is written later by Insight::BodyWriter, and only when the+# insight is new or its numbers changed, so nightly re-runs don't re-invoke+# the LLM for unchanged insights.+class Insight::Generator+ # `facts` doubles as the i18n interpolation args for the template fallback+ # and as the grounding data handed to the LLM writer. `metadata` is what the+ # job compares between runs to decide whether an insight changed — keep its+ # values JSON-primitive (floats, strings, ISO dates) so comparisons are stable.+ GeneratedInsight = Data.define(+ :insight_type,+ :priority,+ :title,+ :template_key,+ :facts,+ :metadata,+ :currency,+ :period_start,+ :period_end,+ :dedup_key+ )++ class << self+ # Declares the insight_type values this generator can emit. The job uses+ # this to expire stale insights: a visible insight whose type belongs to a+ # generator that ran successfully, but whose dedup_key was not regenerated,+ # has had its condition clear.+ def produces(*types)+ @produced_types = types.flatten.map(&:to_s)+ end++ def produced_types+ @produced_types || []+ end+ end++ def initialize(family)+ @family = family+ end++ def generate+ raise NotImplementedError+ end++ private+ attr_reader :family++ def income_statement+ @income_statement ||= IncomeStatement.new(family)+ end++ def balance_sheet+ @balance_sheet ||= BalanceSheet.new(family)+ end++ def build_insight(insight_type:, priority:, title:, template_key:, facts:, dedup_key:, metadata:, period: nil)+ GeneratedInsight.new(+ insight_type: insight_type,+ priority: priority,+ title: title,+ template_key: template_key,+ facts: facts,+ metadata: metadata,+ currency: family.currency,+ period_start: period&.start_date,+ period_end: period&.end_date,+ dedup_key: dedup_key+ )+ end++ def format_money(amount)+ Money.new(amount, family.currency).format+ end++ # Normalizes BigDecimal/Rational math results so metadata survives a jsonb+ # round-trip unchanged (BigDecimal#as_json is a string, which would make+ # every nightly run look like a material change).+ def round(amount, precision = 2)+ amount.to_f.round(precision)+ end++ def month_token(date = Date.current)+ date.strftime("%Y-%m")+ end++ # Formats a number for display facts with a true minus sign (U+2212) —+ # the app types negatives with a minus, not a hyphen. Keep raw numerics+ # in `metadata`; this is for interpolation into template/LLM prose only.+ def signed_number(value)+ value.negative? ? "−#{value.abs}" : value.to_s+ end+enddiff --git a/app/models/insight/generator_registry.rb b/app/models/insight/generator_registry.rbnew file mode 100644index 0000000000..3fb9287926--- /dev/null+++ b/app/models/insight/generator_registry.rb@@ -0,0 +1,46 @@+# Runs every insight generator for a family. A failing generator is logged to+# the super-admin debug UI and skipped, so one bad signal never blocks the rest+# of the nightly run. The result records which insight types were produced by+# generators that ran to completion — the job only expires stale insights of+# those types, so a crashing generator can never wipe out its healthy insights.+class Insight::GeneratorRegistry+ GENERATORS = [+ Insight::Generators::SpendingAnomalyGenerator,+ Insight::Generators::CashFlowWarningGenerator,+ Insight::Generators::NetWorthMilestoneGenerator,+ Insight::Generators::SubscriptionAuditGenerator,+ Insight::Generators::SavingsRateChangeGenerator,+ Insight::Generators::IdleCashGenerator,+ Insight::Generators::BudgetInsightGenerator+ ].freeze++ Result = Data.define(:insights, :succeeded_types)++ def initialize(family)+ @family = family+ end++ def generate_all+ insights = []+ succeeded_types = []++ GENERATORS.each do |generator_class|+ insights.concat(generator_class.new(family).generate)+ succeeded_types.concat(generator_class.produced_types)+ rescue => e+ DebugLogEntry.capture(+ category: "insights",+ level: "error",+ message: "#{generator_class.name} failed: #{e.class}: #{e.message}",+ source: "Insight::GeneratorRegistry",+ family: family,+ metadata: { generator: generator_class.name, backtrace: e.backtrace&.first(5) }+ )+ end++ Result.new(insights: insights, succeeded_types: succeeded_types)+ end++ private+ attr_reader :family+enddiff --git a/app/models/insight/generators/budget_insight_generator.rb b/app/models/insight/generators/budget_insight_generator.rbnew file mode 100644index 0000000000..9e2b173f52--- /dev/null+++ b/app/models/insight/generators/budget_insight_generator.rb@@ -0,0 +1,92 @@+# Reads the family's current budget (if they've set one up) and produces+# either a warning — categories over or near their limit — or, once the month+# is at least half over, a quiet positive signal that everything is on track.+# Reuses BudgetCategory's own health checks rather than re-deriving pace math.+class Insight::Generators::BudgetInsightGenerator < Insight::Generator+ produces "budget_at_risk", "budget_on_track"++ NEAR_LIMIT_MIN_ELAPSED = 0.0 # near-limit/over warnings fire any time+ ON_TRACK_MIN_ELAPSED = 0.5 # positive signal only once the month is half over+ MAX_LISTED_CATEGORIES = 3++ def generate+ budget = current_budget+ return [] unless budget&.initialized?++ parent_categories = budget.budget_categories.reject(&:subcategory?)+ over = parent_categories.select(&:over_budget_with_budget?)+ near = parent_categories.select { |bc| bc.budgeted? && bc.near_limit? }++ if over.any? || near.any?+ [ at_risk_insight(budget, over, near) ]+ elsif on_track_eligible?(budget, parent_categories)+ [ on_track_insight(budget) ]+ else+ []+ end+ end++ private+ def current_budget+ family.budgets+ .includes(budget_categories: :category)+ .where("start_date <= ? AND end_date >= ?", Date.current, Date.current)+ .first+ end++ def at_risk_insight(budget, over, near)+ flagged = over + near+ category_names = flagged.first(MAX_LISTED_CATEGORIES).map { |bc| bc.category.name }++ build_insight(+ insight_type: "budget_at_risk",+ priority: over.any? ? "high" : "medium",+ title: I18n.t("insights.titles.budget_at_risk", count: flagged.size),+ template_key: over.any? ? "budget_at_risk.over" : "budget_at_risk.near",+ facts: {+ categories: category_names.to_sentence,+ count: flagged.size,+ budget_spent_pct: round(budget.percent_of_budget_spent, 0).to_i+ },+ # The percent bucket keeps the body fresh as overall usage moves (a+ # >=10-point swing rewrites it) without nightly one-point churn.+ metadata: {+ over_category_ids: over.map { |bc| bc.category.id }.sort,+ near_category_ids: near.map { |bc| bc.category.id }.sort,+ budget_spent_pct_bucket: (round(budget.percent_of_budget_spent, 0).to_i / 10) * 10+ },+ period: budget.period,+ dedup_key: "budget_at_risk:#{month_token(budget.start_date)}"+ )+ end++ def on_track_insight(budget)+ build_insight(+ insight_type: "budget_on_track",+ priority: "low",+ title: I18n.t("insights.titles.budget_on_track"),+ template_key: "budget_on_track",+ facts: {+ spent: format_money(budget.actual_spending),+ budgeted: format_money(budget.budgeted_spending),+ budget_spent_pct: round(budget.percent_of_budget_spent, 0).to_i+ },+ # Bucketed to damp nightly churn: a one-point move shouldn't count as+ # a material change that rewrites the body or reactivates a dismissal.+ metadata: {+ budget_spent_pct_bucket: (round(budget.percent_of_budget_spent, 0).to_i / 10) * 10+ },+ period: budget.period,+ dedup_key: "budget_on_track:#{month_token(budget.start_date)}"+ )+ end++ def on_track_eligible?(budget, parent_categories)+ return false unless parent_categories.any?(&:budgeted?)++ total_days = (budget.end_date - budget.start_date).to_i + 1+ elapsed_days = (Date.current - budget.start_date).to_i + 1++ elapsed_days.to_f / total_days >= ON_TRACK_MIN_ELAPSED+ end+enddiff --git a/app/models/insight/generators/cash_flow_warning_generator.rb b/app/models/insight/generators/cash_flow_warning_generator.rbnew file mode 100644index 0000000000..36ed14bf20--- /dev/null+++ b/app/models/insight/generators/cash_flow_warning_generator.rb@@ -0,0 +1,88 @@+# Projects the family's combined cash (Depository) balance forward 30 days by+# layering known recurring transactions on top of a statistical daily-spend+# baseline, and warns when the projected balance dips below the threshold.+class Insight::Generators::CashFlowWarningGenerator < Insight::Generator+ produces "cash_flow_warning"++ # Known limitation: family-currency units, tuned for dollar/euro-scale+ # currencies (¥500 ≈ $3 would make this threshold meaninglessly low).+ LOW_BALANCE_THRESHOLD = 500+ HORIZON_DAYS = 30++ def generate+ accounts = cash_accounts+ return [] if accounts.empty?++ starting_balance = accounts.sum(:balance).to_d+ entries = upcoming_recurring_entries+ recurring_by_date = entries.group_by(&:date)++ # The recurring bills are part of the monthly median too — subtract them so+ # they aren't counted twice when we spread the remainder across the horizon.+ median_monthly_expense = income_statement.median_expense(interval: "month").to_d+ return [] if median_monthly_expense <= 0 && entries.empty?++ recurring_expense_total = entries.sum { |e| [ e.amount.to_d, 0.to_d ].max }+ other_daily_spend = [ median_monthly_expense - recurring_expense_total, 0.to_d ].max / HORIZON_DAYS++ balance = starting_balance+ low_point = starting_balance+ low_date = Date.current++ (1..HORIZON_DAYS).each do |offset|+ date = Date.current + offset+ balance -= other_daily_spend+ recurring_by_date.fetch(date, []).each { |e| balance -= e.amount.to_d }++ if balance < low_point+ low_point = balance+ low_date = date+ end+ end++ return [] if low_point >= LOW_BALANCE_THRESHOLD++ template_key = low_point.negative? ? "cash_flow_warning.negative" : "cash_flow_warning.low"++ [+ build_insight(+ insight_type: "cash_flow_warning",+ priority: low_point.negative? ? "high" : "medium",+ title: I18n.t("insights.titles.#{template_key}"),+ template_key: template_key,+ facts: {+ projected_low: format_money(low_point),+ projected_low_date: I18n.l(low_date),+ current_balance: format_money(starting_balance),+ horizon_days: HORIZON_DAYS+ },+ # Balances and projected dates drift with nearly every transaction, so+ # exact values here would read as a material change nightly — rewriting+ # the body and resurrecting dismissals. Only severity and a coarse+ # bucket of the low point are material; display values live in `facts`.+ metadata: {+ negative: low_point.negative?,+ projected_low_bucket: (round(low_point, 0).to_i / 250) * 250+ },+ period: Period.custom(start_date: Date.current, end_date: Date.current + HORIZON_DAYS),+ dedup_key: "cash_flow_warning:#{month_token}"+ )+ ]+ end++ private+ def cash_accounts+ family.accounts.visible.where(accountable_type: "Depository", currency: family.currency)+ end++ # Projected occurrences of known recurring transactions within the horizon.+ # Transfers are internal moves, and cross-currency amounts can't be applied+ # to a family-currency balance without a rate lookup, so both are skipped.+ def upcoming_recurring_entries+ family.recurring_transactions+ .expected_soon+ .where(destination_account_id: nil)+ .filter_map(&:projected_entry)+ .select { |e| e.currency == family.currency && e.date <= Date.current + HORIZON_DAYS }+ end+enddiff --git a/app/models/insight/generators/idle_cash_generator.rb b/app/models/insight/generators/idle_cash_generator.rbnew file mode 100644index 0000000000..651e6b5bb3--- /dev/null+++ b/app/models/insight/generators/idle_cash_generator.rb@@ -0,0 +1,44 @@+# Points out sizable cash balances that have sat untouched for a while. Low+# priority by design — it's a nudge, not a warning. The dedup key rotates+# monthly so a dismissed nudge stays gone for the rest of the month.+class Insight::Generators::IdleCashGenerator < Insight::Generator+ produces "idle_cash"++ # Known limitation: family-currency units, tuned for dollar/euro-scale+ # currencies (¥5,000 ≈ $33 would make this fire on trivial balances).+ MIN_BALANCE = 5_000+ IDLE_DAYS = 60+ MAX_INSIGHTS = 2++ def generate+ idle_accounts.first(MAX_INSIGHTS).map do |account|+ build_insight(+ insight_type: "idle_cash",+ priority: "low",+ title: I18n.t("insights.titles.idle_cash", account: account.name),+ template_key: "idle_cash",+ facts: {+ account: account.name,+ balance: format_money(account.balance),+ idle_days: IDLE_DAYS+ },+ metadata: {+ account_id: account.id,+ balance: round(account.balance, 0)+ },+ dedup_key: "idle_cash:#{account.id}:#{month_token}"+ )+ end+ end++ private+ # Ordered so the pick is stable between runs — an unordered relation could+ # nudge a different pair of accounts each night, churning the feed.+ def idle_accounts+ family.accounts.visible+ .where(accountable_type: "Depository", currency: family.currency)+ .where("balance >= ?", MIN_BALANCE)+ .where.not(id: Entry.where("date >= ?", IDLE_DAYS.days.ago.to_date).select(:account_id))+ .order(balance: :desc)+ end+enddiff --git a/app/models/insight/generators/net_worth_milestone_generator.rb b/app/models/insight/generators/net_worth_milestone_generator.rbnew file mode 100644index 0000000000..5ba4bf363d--- /dev/null+++ b/app/models/insight/generators/net_worth_milestone_generator.rb@@ -0,0 +1,58 @@+# Celebrates the family's net worth crossing a round-number milestone within+# the last 30 days. The dedup key is the milestone amount itself, so a+# milestone row is reused for life: a dismissal is permanent, and only a+# dip-below-and-recross within a 30-day window can resurface an expired one.+class Insight::Generators::NetWorthMilestoneGenerator < Insight::Generator+ produces "net_worth_milestone"++ # Known limitation: milestones are family-currency units, tuned for+ # dollar/euro-scale currencies. In JPY-scale currencies the lower rungs are+ # trivially small ($10k ≈ ¥1.5M would be the right first rung, not ¥10k).+ MILESTONES = [+ 10_000, 25_000, 50_000, 100_000, 250_000,+ 500_000, 1_000_000, 2_500_000, 5_000_000, 10_000_000+ ].freeze++ def generate+ series = balance_sheet.net_worth_series(period: Period.last_30_days)+ values = series.values+ return [] if values.size < 2++ current = money_amount(values.last.value)+ previous = money_amount(values.first.value)+ return [] if current <= previous++ milestone = MILESTONES.select { |m| previous < m && current >= m }.max+ return [] unless milestone++ [+ build_insight(+ insight_type: "net_worth_milestone",+ priority: "high",+ title: I18n.t("insights.titles.net_worth_milestone", milestone: format_whole_money(milestone)),+ template_key: "net_worth_milestone",+ facts: {+ milestone: format_whole_money(milestone),+ net_worth: format_money(current)+ },+ # The milestone alone is the signal. Net worth itself drifts daily for+ # the ~30 days the crossing stays in the series window — storing it+ # here would rewrite the body and resurrect dismissals every night.+ metadata: {+ milestone: milestone+ },+ period: Period.last_30_days,+ dedup_key: "net_worth_milestone:#{milestone}"+ )+ ]+ end++ private+ def money_amount(value)+ (value.respond_to?(:amount) ? value.amount : value).to_d+ end++ def format_whole_money(amount)+ Money.new(amount, family.currency).format(precision: 0)+ end+enddiff --git a/app/models/insight/generators/savings_rate_change_generator.rb b/app/models/insight/generators/savings_rate_change_generator.rbnew file mode 100644index 0000000000..11f606c9ca--- /dev/null+++ b/app/models/insight/generators/savings_rate_change_generator.rb@@ -0,0 +1,63 @@+# Compares the savings rate of the last two complete months. The current+# (partial) month is skipped on purpose — income usually lands early or late+# in a month, which makes mid-month rates meaningless.+class Insight::Generators::SavingsRateChangeGenerator < Insight::Generator+ produces "savings_rate_change"++ THRESHOLD_PP = 5+ HIGH_PRIORITY_PP = 10++ def generate+ last_month = Period.last_month_for(family)+ prior_start = last_month.start_date - 1.month+ prior_month = Period.custom(start_date: prior_start, end_date: last_month.start_date - 1.day)++ current_rate = savings_rate(last_month)+ previous_rate = savings_rate(prior_month)+ return [] unless current_rate && previous_rate++ delta = current_rate - previous_rate+ return [] if delta.abs < THRESHOLD_PP++ direction = delta.positive? ? "up" : "down"+ month_name = I18n.l(last_month.start_date, format: "%B")++ # "You saved -5.4% of your income" is machine-speak; a negative rate means+ # the family spent more than it earned, and the copy should say so.+ template_key = if direction == "down" && current_rate.negative?+ "savings_rate_change.down_negative"+ else+ "savings_rate_change.#{direction}"+ end++ [+ build_insight(+ insight_type: "savings_rate_change",+ priority: delta.abs >= HIGH_PRIORITY_PP ? "high" : "medium",+ title: I18n.t("insights.titles.savings_rate_change.#{direction}", month: month_name),+ template_key: template_key,+ facts: {+ month: month_name,+ current_rate: signed_number(round(current_rate, 1)),+ previous_rate: signed_number(round(previous_rate, 1)),+ change_pp: round(delta.abs, 1)+ },+ metadata: {+ current_rate: round(current_rate, 1),+ previous_rate: round(previous_rate, 1)+ },+ period: last_month,+ dedup_key: "savings_rate_change:#{month_token(last_month.start_date)}"+ )+ ]+ end++ private+ def savings_rate(period)+ income = income_statement.income_totals(period: period).total.to_d+ return nil if income <= 0++ expense = income_statement.expense_totals(period: period).total.to_d+ (income - expense) / income * 100+ end+enddiff --git a/app/models/insight/generators/spending_anomaly_generator.rb b/app/models/insight/generators/spending_anomaly_generator.rbnew file mode 100644index 0000000000..4c739baade--- /dev/null+++ b/app/models/insight/generators/spending_anomaly_generator.rb@@ -0,0 +1,97 @@+# Flags parent categories whose current-month spending pace deviates from+# their average over the previous three full months.+class Insight::Generators::SpendingAnomalyGenerator < Insight::Generator+ produces "spending_anomaly"++ MIN_BASELINE = 50 # ignore categories with a negligible baseline+ MIN_ELAPSED_DAYS = 7 # too early in the month = too noisy to project+ DEVIATION_THRESHOLD_PCT = 25+ HIGH_PRIORITY_PCT = 50+ BASELINE_MONTHS = 3+ MAX_INSIGHTS = 3++ def generate+ period = Period.current_month_for(family)+ elapsed_days = (Date.current - period.start_date).to_i + 1+ return [] if elapsed_days < MIN_ELAPSED_DAYS++ current = category_spend(period)+ return [] if current.empty?++ baseline = baseline_spend(period)+ pace_factor = period.days.to_f / elapsed_days++ anomalies = current.filter_map do |category_id, data|+ baseline_amount = baseline[category_id]+ next unless baseline_amount && baseline_amount >= MIN_BASELINE++ projected = data[:total] * pace_factor+ deviation_pct = (projected - baseline_amount) / baseline_amount * 100+ next if deviation_pct.abs < DEVIATION_THRESHOLD_PCT++ { category_id: category_id, name: data[:name], projected: projected,+ baseline: baseline_amount, deviation_pct: deviation_pct }+ end++ anomalies+ .sort_by { |a| -a[:deviation_pct].abs }+ .first(MAX_INSIGHTS)+ .map { |anomaly| anomaly_insight(anomaly, period) }+ end++ private+ def anomaly_insight(anomaly, period)+ direction = anomaly[:deviation_pct].positive? ? "above" : "below"++ build_insight(+ insight_type: "spending_anomaly",+ priority: anomaly[:deviation_pct].abs >= HIGH_PRIORITY_PCT ? "high" : "medium",+ title: I18n.t("insights.titles.spending_anomaly.#{direction}", category: anomaly[:name]),+ template_key: "spending_anomaly.#{direction}",+ facts: {+ category: anomaly[:name],+ deviation_pct: round(anomaly[:deviation_pct].abs, 0).to_i,+ projected_spend: format_money(anomaly[:projected]),+ baseline_spend: format_money(anomaly[:baseline])+ },+ # The projection moves every night by construction (spend accrues and+ # the pace factor shrinks as the month elapses), so exact amounts here+ # would rewrite the body and resurrect dismissals nightly. Bucket the+ # deviation instead; the display numbers live in `facts` only.+ metadata: {+ category_id: anomaly[:category_id],+ direction: direction,+ deviation_bucket: (round(anomaly[:deviation_pct].abs, 0).to_i / 25) * 25+ },+ period: period,+ dedup_key: "spending_anomaly:#{anomaly[:category_id]}:#{month_token(period.start_date)}"+ )+ end++ # { category_id => { name:, total: } } for persisted parent categories only.+ # Subcategory spend is already rolled into its parent's total, and synthetic+ # categories (uncategorized / other investments) are too noisy to flag.+ def category_spend(period)+ income_statement.expense_totals(period: period).category_totals.each_with_object({}) do |ct, totals|+ next if ct.category.synthetic? || ct.category.parent_id.present?+ next unless ct.total.positive?++ totals[ct.category.id] = { name: ct.category.name, total: ct.total.to_d }+ end+ end++ def baseline_spend(current_period)+ sums = Hash.new { |h, k| h[k] = 0.to_d }++ BASELINE_MONTHS.times do |i|+ start_date = current_period.start_date - (i + 1).months+ month = Period.custom(start_date: start_date, end_date: start_date + 1.month - 1.day)++ category_spend(month).each do |category_id, data|+ sums[category_id] += data[:total]+ end+ end++ sums.transform_values { |total| total / BASELINE_MONTHS }+ end+enddiff --git a/app/models/insight/generators/subscription_audit_generator.rb b/app/models/insight/generators/subscription_audit_generator.rbnew file mode 100644index 0000000000..dbbae89525--- /dev/null+++ b/app/models/insight/generators/subscription_audit_generator.rb@@ -0,0 +1,50 @@+# Surfaces recurring expenses that are well past their expected date — the+# provider may have raised the price, the charge may have moved, or the user+# may be paying for something that quietly stopped (or should stop).+class Insight::Generators::SubscriptionAuditGenerator < Insight::Generator+ produces "subscription_audit"++ OVERDUE_DAYS = 45+ MAX_INSIGHTS = 3++ def generate+ overdue_recurring.map do |recurring|+ name = recurring.merchant&.name.presence || recurring.name+ amount = Money.new(recurring.amount, recurring.currency).format+ days_overdue = (Date.current - recurring.next_expected_date).to_i++ build_insight(+ insight_type: "subscription_audit",+ priority: "medium",+ title: I18n.t("insights.titles.subscription_audit", name: name),+ template_key: "subscription_audit",+ facts: {+ name: name,+ amount: amount,+ days_overdue: days_overdue,+ expected_on: I18n.l(recurring.next_expected_date)+ },+ # days_overdue is deliberately left out: it changes every night, and+ # metadata drift would resurrect insights the user already dismissed.+ metadata: {+ recurring_transaction_id: recurring.id,+ amount: round(recurring.amount, 2),+ expected_on: recurring.next_expected_date.iso8601+ },+ dedup_key: "subscription_audit:#{recurring.id}"+ )+ end+ end++ private+ def overdue_recurring+ family.recurring_transactions+ .includes(:merchant)+ .active+ .where(destination_account_id: nil)+ .where("amount > 0")+ .where("next_expected_date < ?", OVERDUE_DAYS.days.ago.to_date)+ .order(:next_expected_date)+ .limit(MAX_INSIGHTS)+ end+enddiff --git a/app/models/user.rb b/app/models/user.rbindex f1c6fbb9ac..8938c2d752 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -456,7 +456,7 @@ class User < ApplicationRecordenddef default_dashboard_section_order- %w[cashflow_sankey outflows_donut net_worth_chart balance_sheet]+ %w[insights_feed cashflow_sankey outflows_donut net_worth_chart balance_sheet]enddef default_reports_section_orderdiff --git a/app/views/insights/_insight_card.html.erb b/app/views/insights/_insight_card.html.erbnew file mode 100644index 0000000000..95d211f057--- /dev/null+++ b/app/views/insights/_insight_card.html.erb@@ -0,0 +1,46 @@+<%# locals: (insight:, unread: false) %>++<div id="<%= dom_id(insight) %>" class="bg-container rounded-xl shadow-border-xs p-4 flex gap-3">+ <div class="shrink-0 mt-0.5">+ <%= icon(insight_icon_key(insight), color: insight_icon_color(insight)) %>+ </div>++ <div class="min-w-0 grow space-y-1">+ <p class="text-xs text-secondary"><%= insight_meta_line(insight) %></p>++ <div class="flex items-start justify-between gap-3">+ <h3 class="text-sm font-medium text-primary inline-flex items-center gap-2 min-w-0">+ <%= insight.title %>+ <% if unread %>+ <%= render DS::Pill.new(label: t("insights.card.new"), tone: :info, size: :sm) %>+ <% end %>+ </h3>++ <div class="flex items-start gap-1 shrink-0">+ <% if (figure = insight_key_figure(insight)) %>+ <div class="text-right mr-1">+ <p class="text-sm font-mono font-medium privacy-sensitive <%= insight_sentiment(insight) == :positive ? "text-success" : "text-primary" %>"><%= figure.first %></p>+ <p class="text-xs text-subdued"><%= figure.last %></p>+ </div>+ <% end %>++ <%= render DS::Button.new(+ variant: "icon",+ icon: "x",+ href: dismiss_insight_path(insight),+ method: :patch,+ title: t("insights.card.dismiss"),+ aria_label: t("insights.card.dismiss")+ ) %>+ </div>+ </div>++ <p class="text-sm text-secondary"><%= insight.body %></p>++ <% if (action = insight_action(insight)) %>+ <div class="pt-1">+ <%= render DS::Link.new(text: action[:text], href: action[:href], variant: "ghost", size: "sm") %>+ </div>+ <% end %>+ </div>+</div>diff --git a/app/views/insights/_list.html.erb b/app/views/insights/_list.html.erbnew file mode 100644index 0000000000..da1f7c51c1--- /dev/null+++ b/app/views/insights/_list.html.erb@@ -0,0 +1,16 @@+<%# locals: (insights:, unread_ids:) %>++<div id="insights-list" class="space-y-3">+ <% if insights.any? %>+ <% insights.each do |insight| %>+ <%= render "insights/insight_card", insight: insight, unread: unread_ids.include?(insight.id) %>+ <% end %>+ <% else %>+ <%= render DS::EmptyState.new(+ icon: "icon-assistant",+ icon_custom: true,+ title: t("insights.index.empty.title"),+ description: t("insights.index.empty.description")+ ) %>+ <% end %>+</div>diff --git a/app/views/insights/_refresh_button.html.erb b/app/views/insights/_refresh_button.html.erbnew file mode 100644index 0000000000..5957105483--- /dev/null+++ b/app/views/insights/_refresh_button.html.erb@@ -0,0 +1,20 @@+<%# locals: (pending: false) %>++<div id="insights-refresh">+ <% if pending %>+ <%= render DS::Button.new(+ text: t("insights.refresh.checking"),+ variant: "outline",+ icon: "loader-circle",+ disabled: true+ ) %>+ <% else %>+ <%= render DS::Button.new(+ text: t("insights.index.refresh"),+ variant: "outline",+ icon: "refresh-cw",+ href: refresh_insights_path,+ method: :post+ ) %>+ <% end %>+</div>diff --git a/app/views/insights/_undo_toast.html.erb b/app/views/insights/_undo_toast.html.erbnew file mode 100644index 0000000000..203f19e777--- /dev/null+++ b/app/views/insights/_undo_toast.html.erb@@ -0,0 +1,19 @@+<%# locals: (insight:) %>++<div id="<%= dom_id(insight, :undo) %>"+ class="relative flex items-center gap-3 rounded-lg bg-container p-4 group w-full md:max-w-80 shadow-border-xs"+ data-controller="element-removal">+ <p class="text-primary text-sm font-medium grow"><%= t("insights.card.dismissed") %></p>++ <%= render DS::Button.new(+ text: t("insights.card.undo"),+ variant: "ghost",+ size: "sm",+ href: undismiss_insight_path(insight),+ method: :patch+ ) %>++ <%= icon "x",+ class: "p-0.5 rounded-lg text-subdued hover:text-primary cursor-pointer shrink-0",+ data: { action: "click->element-removal#remove" } %>+</div>diff --git a/app/views/insights/dismiss.turbo_stream.erb b/app/views/insights/dismiss.turbo_stream.erbnew file mode 100644index 0000000000..8b51de9292--- /dev/null+++ b/app/views/insights/dismiss.turbo_stream.erb@@ -0,0 +1,5 @@+<%= turbo_stream.remove dom_id(@insight) %>++<%= turbo_stream.append "notification-tray" do %>+ <%= render "insights/undo_toast", insight: @insight %>+<% end %>diff --git a/app/views/insights/index.html.erb b/app/views/insights/index.html.erbnew file mode 100644index 0000000000..3b360f8698--- /dev/null+++ b/app/views/insights/index.html.erb@@ -0,0 +1,14 @@+<%= turbo_stream_from Current.family, :insights %>++<div class="space-y-6 pb-6">+ <header class="flex items-start justify-between gap-4">+ <div>+ <h1 class="text-2xl font-semibold text-primary"><%= t(".title") %></h1>+ <p class="text-sm text-secondary mt-1"><%= t(".subtitle") %></p>+ </div>++ <%= render "insights/refresh_button", pending: false %>+ </header>++ <%= render "insights/list", insights: @insights, unread_ids: @unread_ids %>+</div>diff --git a/app/views/insights/refresh.turbo_stream.erb b/app/views/insights/refresh.turbo_stream.erbnew file mode 100644index 0000000000..02ddb01a9d--- /dev/null+++ b/app/views/insights/refresh.turbo_stream.erb@@ -0,0 +1,3 @@+<%= turbo_stream.replace "insights-refresh" do %>+ <%= render "insights/refresh_button", pending: true %>+<% end %>diff --git a/app/views/insights/undismiss.turbo_stream.erb b/app/views/insights/undismiss.turbo_stream.erbnew file mode 100644index 0000000000..d572c8da3e--- /dev/null+++ b/app/views/insights/undismiss.turbo_stream.erb@@ -0,0 +1,5 @@+<%= turbo_stream.remove dom_id(@insight, :undo) %>++<%= turbo_stream.replace "insights-list" do %>+ <%= render "insights/list", insights: @insights, unread_ids: @unread_ids %>+<% end %>diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erbindex 0f07cfedd4..0d135ba6d9 100644--- a/app/views/layouts/application.html.erb+++ b/app/views/layouts/application.html.erb@@ -159,6 +159,23 @@ end %></div><div class="flex items-center gap-2">+ <% if Current.family %>+ <% unread_insights_count = Current.family.insights.active.count %>+ <%# Prefetch disabled: /insights marks insights read on real visits+ and deliberately skips prefetch requests, so a prefetched+ response served on click would never clear the badge. %>+ <%= link_to insights_path,+ class: "relative inline-flex items-center justify-center w-9 h-9 pointer-coarse:w-11 pointer-coarse:h-11 rounded-lg text-secondary hover:text-primary hover:bg-container-inset-hover transition-colors focus-ring",+ title: t("layouts.application.insights"),+ aria: { label: t("layouts.application.insights") },+ data: { turbo_prefetch: false } do %>+ <%= icon("lightbulb", size: "sm") %>+ <% if unread_insights_count.positive? %>+ <span class="absolute top-1 right-1 min-w-4 h-4 px-1 rounded-full bg-inverse text-inverse text-[10px] font-medium flex items-center justify-center pointer-events-none"><%= unread_insights_count > 9 ? "9+" : unread_insights_count %></span>+ <% end %>+ <% end %>+ <% end %>+<button type="button"class="inline-flex items-center justify-center w-9 h-9 pointer-coarse:w-11 pointer-coarse:h-11 rounded-lg text-secondary hover:text-primary hover:bg-container-inset-hover transition-colors focus-ring"data-action="click->privacy-mode#toggle"diff --git a/app/views/pages/dashboard/_insights_feed.html.erb b/app/views/pages/dashboard/_insights_feed.html.erbnew file mode 100644index 0000000000..e6132d9607--- /dev/null+++ b/app/views/pages/dashboard/_insights_feed.html.erb@@ -0,0 +1,64 @@+<%# locals: (insights:, **args) %>++<%# Mirrors the outflows/balance-sheet list idiom: an inset well with an+ uppercase mini-header, white rows inside, tinted icon circles, and+ right-aligned figures. Dismissal lives on /insights; here each row just+ links through. Prefetch is disabled because Turbo would serve the+ hover-prefetched response on click, skipping the mark-as-read in+ InsightsController#index (it deliberately ignores prefetch requests). %>+<%# -mt-2 evens the frame: the section shell gives 24px above the content but+ only 16px at the sides and bottom, and with the well as the sole content+ the asymmetry shows. %>+<div id="insights-feed" class="px-4 -mt-2">+ <div class="bg-container-inset rounded-xl p-1 space-y-1">+ <div class="px-4 py-2 flex items-center justify-between uppercase text-xs font-medium text-secondary">+ <% new_count = insights.count(&:active?) %>+ <% if new_count.positive? %>+ <p><%= t("insights.feed.header_new") %><span class="text-subdued mx-1">·</span><%= new_count %></p>+ <% else %>+ <p><%= t("insights.feed.header") %></p>+ <% end %>++ <%= render DS::Link.new(+ text: t("insights.feed.view_all"),+ href: insights_path,+ variant: "ghost",+ size: "sm",+ class: "normal-case",+ data: { turbo_prefetch: false }+ ) %>+ </div>++ <div class="py-1.5 shadow-border-xs rounded-lg bg-container text-sm">+ <% insights.each do |insight| %>+ <%# No hover background, matching the outflows rows — the affordance is+ the cursor plus the icon's gentle scale. %>+ <%= link_to insights_path,+ data: { turbo_prefetch: false },+ class: "flex items-center mx-3 px-3 py-2.5 rounded-lg gap-3 cursor-pointer group" do %>+ <div class="h-7 w-7 shrink-0 rounded-full flex justify-center items-center group-hover:scale-105 transition-all duration-300"+ style="background-color: color-mix(in oklab, <%= insight_icon_css_color(insight) %> 10%, transparent); color: <%= insight_icon_css_color(insight) %>;">+ <%= icon(insight_icon_key(insight), color: "current", size: "sm") %>+ </div>++ <div class="min-w-0 grow">+ <div class="flex items-center gap-2">+ <span class="text-sm font-medium text-primary truncate"><%= insight.title %></span>+ <% if insight.active? %>+ <%= render DS::Pill.new(label: t("insights.card.new"), tone: :info, size: :sm) %>+ <% end %>+ </div>+ <p class="text-sm text-secondary truncate"><%= insight.body %></p>+ </div>++ <% if (figure = insight_key_figure(insight)) %>+ <div class="text-right shrink-0">+ <p class="text-sm font-medium whitespace-nowrap privacy-sensitive <%= insight_sentiment(insight) == :positive ? "text-success" : "text-primary" %>"><%= figure.first %></p>+ <p class="text-xs text-secondary whitespace-nowrap"><%= figure.last %></p>+ </div>+ <% end %>+ <% end %>+ <% end %>+ </div>+ </div>+</div>diff --git a/config/locales/views/insights/en.yml b/config/locales/views/insights/en.ymlnew file mode 100644index 0000000000..fccc31a064--- /dev/null+++ b/config/locales/views/insights/en.yml@@ -0,0 +1,93 @@+---+en:+ insights:+ index:+ title: Insights+ subtitle: What's happening across your finances, refreshed nightly.+ refresh: Check for new insights+ empty:+ title: No insights yet+ description: Insights appear here once there's enough activity in your accounts. They refresh automatically every night.+ refresh:+ queued: We're generating fresh insights. Check back in a minute.+ checking: Checking…+ card:+ dismiss: Dismiss+ new: New+ dismissed: Insight dismissed+ undo: Undo+ feed:+ view_all: View all insights+ header: Latest+ header_new: New+ types:+ spending_anomaly: Spending+ cash_flow_warning: Cash flow+ net_worth_milestone: Net worth+ subscription_audit: Subscriptions+ savings_rate_change: Savings rate+ idle_cash: Idle cash+ budget_at_risk: Budget+ budget_on_track: Budget+ meta:+ next_n_days:+ one: Next day+ other: Next %{count} days+ last_n_days:+ one: Last day+ other: Last %{count} days+ date_range: "%{from} to %{to}"+ figures:+ vs_previous: vs prior month+ today: today+ on_pace: on pace+ of_budget: of budget+ days_overdue:+ one: "%{count} day overdue"+ other: "%{count} days overdue"+ idle_days:+ one: idle %{count} day+ other: idle %{count} days+ actions:+ spending_anomaly: View %{category} transactions+ cash_flow_warning: Review recurring transactions+ net_worth_milestone: View net worth report+ subscription_audit: Review recurring transactions+ savings_rate_change: View that month's transactions+ idle_cash: Go to account+ budget: View budget+ titles:+ spending_anomaly:+ above: "%{category} spending is trending up"+ below: "%{category} spending is trending down"+ cash_flow_warning:+ low: Your cash balance may run low+ negative: Your cash balance may go negative+ net_worth_milestone: "Net worth milestone: %{milestone}"+ subscription_audit: "Is %{name} still active?"+ savings_rate_change:+ up: Your savings rate improved in %{month}+ down: Your savings rate dropped in %{month}+ idle_cash: Idle cash in %{account}+ budget_at_risk:+ one: One category needs attention in your budget+ other: "%{count} categories need attention in your budget"+ budget_on_track: Your budget is on track+ 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}.+ below: You're on pace to spend %{projected_spend} on %{category} this month, about %{deviation_pct}% less than your recent monthly average of %{baseline_spend}.+ cash_flow_warning:+ 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}.+ 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.+ down: You saved %{current_rate}% of your income in %{month}, down %{change_pp} percentage points from %{previous_rate}% the month before.+ down_negative: "You spent more than you earned in %{month}: your savings rate fell to %{current_rate}%, from %{previous_rate}% the month before."+ idle_cash: "%{account} holds %{balance} with no activity in the last %{idle_days} days."+ budget_at_risk:+ 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.diff --git a/config/locales/views/layout/en.yml b/config/locales/views/layout/en.ymlindex 0d5526a2ff..49f3125593 100644--- a/config/locales/views/layout/en.yml+++ b/config/locales/views/layout/en.yml@@ -2,6 +2,7 @@en:layouts:application:+ insights: Insightsprivacy_mode: Toggle privacy moderesize_left_sidebar: Resize the accounts sidebarresize_right_sidebar: Resize the assistant sidebardiff --git a/config/locales/views/pages/en.yml b/config/locales/views/pages/en.ymlindex 9b9ff387b8..5b6e6aa74d 100644--- a/config/locales/views/pages/en.yml+++ b/config/locales/views/pages/en.yml@@ -74,6 +74,8 @@ en:classifications:asset: "Assets"liability: "Liabilities"+ insights_feed:+ title: "Insights"cashflow_sankey:title: "Cashflow"zoom_out: "Back to full cashflow"diff --git a/config/routes.rb b/config/routes.rbindex 597d6b8b91..05fa44112e 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -446,6 +446,17 @@ Rails.application.routes.draw doendend+ resources :insights, only: %i[index] do+ collection do+ post :refresh+ end++ member do+ patch :dismiss+ patch :undismiss+ end+ end+resources :accountable_sparklines, only: :show, param: :accountable_typedirect :entry do |entry, options|diff --git a/config/schedule.yml b/config/schedule.ymlindex 6e1c8bb3ad..a504b56986 100644--- a/config/schedule.yml+++ b/config/schedule.yml@@ -49,6 +49,12 @@ refresh_demo_family:queue: "scheduled"description: "Refreshes demo family data and emails super admins with daily usage summary"+generate_insights:+ cron: "0 6 * * *" # daily at 6:00 AM UTC, after the nightly cleanup jobs+ class: "GenerateInsightsJob"+ queue: "scheduled"+ description: "Generates proactive financial insights for all families"+sweep_expired_goal_pledges:cron: "*/15 * * * *" # every 15 minutesclass: "SweepExpiredGoalPledgesJob"diff --git a/db/migrate/20260701120000_create_insights.rb b/db/migrate/20260701120000_create_insights.rbnew file mode 100644index 0000000000..4321f186ac--- /dev/null+++ b/db/migrate/20260701120000_create_insights.rb@@ -0,0 +1,33 @@+class CreateInsights < ActiveRecord::Migration[7.2]+ def change+ create_table :insights, id: :uuid do |t|+ # index: false — every composite index below leads with family_id, so the+ # auto-created single-column index would be redundant write overhead.+ t.references :family, null: false, type: :uuid, foreign_key: true, index: false+ t.string :insight_type, null: false+ t.string :priority, null: false, default: "medium"+ t.string :status, null: false, default: "active"+ t.string :title, null: false+ t.text :body, null: false+ t.jsonb :metadata, null: false, default: {}+ t.string :currency, null: false, default: "USD"+ t.date :period_start+ t.date :period_end+ t.datetime :generated_at, null: false, default: -> { "CURRENT_TIMESTAMP" }+ t.datetime :read_at+ t.datetime :dismissed_at+ # Embeds the insight type and subject, e.g. "spending_anomaly:<category-id>:2026-07",+ # so re-running the nightly job refreshes the existing row instead of duplicating it.+ t.string :dedup_key, null: false++ t.timestamps+ end++ add_check_constraint :insights, "priority IN ('high', 'medium', 'low')", name: "chk_insights_priority"+ add_check_constraint :insights, "status IN ('active', 'read', 'dismissed', 'expired')", name: "chk_insights_status"++ add_index :insights, [ :family_id, :status ]+ add_index :insights, [ :family_id, :dedup_key ], unique: true+ add_index :insights, [ :family_id, :generated_at ]+ end+enddiff --git a/db/migrate/20260713090000_add_facts_to_insights.rb b/db/migrate/20260713090000_add_facts_to_insights.rbnew file mode 100644index 0000000000..e34861c3f1--- /dev/null+++ b/db/migrate/20260713090000_add_facts_to_insights.rb@@ -0,0 +1,8 @@+class AddFactsToInsights < ActiveRecord::Migration[7.2]+ def change+ # Display values (formatted money, localized dates) used to render key+ # figures and contextual links. Refreshed on every run — unlike+ # `metadata`, which holds only the bucketed change-detection signals.+ add_column :insights, :facts, :jsonb, null: false, default: {}+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 6472cee366..e64defa395 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[7.2].define(version: 2026_06_28_200000) do+ActiveRecord::Schema[7.2].define(version: 2026_07_13_090000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pgcrypto"enable_extension "plpgsql"@@ -1152,6 +1152,31 @@ ActiveRecord::Schema[7.2].define(version: 2026_06_28_200000) dot.string "subtype"end+ create_table "insights", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.text "body", null: false+ t.datetime "created_at", null: false+ t.string "currency", default: "USD", null: false+ t.string "dedup_key", null: false+ t.datetime "dismissed_at"+ t.jsonb "facts", default: {}, null: false+ t.uuid "family_id", null: false+ t.datetime "generated_at", default: -> { "CURRENT_TIMESTAMP" }, null: false+ t.string "insight_type", null: false+ t.jsonb "metadata", default: {}, null: false+ t.date "period_end"+ t.date "period_start"+ t.string "priority", default: "medium", null: false+ t.datetime "read_at"+ t.string "status", default: "active", null: false+ t.string "title", null: false+ t.datetime "updated_at", null: false+ t.index ["family_id", "dedup_key"], name: "index_insights_on_family_id_and_dedup_key", unique: true+ t.index ["family_id", "generated_at"], name: "index_insights_on_family_id_and_generated_at"+ t.index ["family_id", "status"], name: "index_insights_on_family_id_and_status"+ t.check_constraint "priority::text = ANY (ARRAY['high'::character varying, 'medium'::character varying, 'low'::character varying]::text[])", name: "chk_insights_priority"+ t.check_constraint "status::text = ANY (ARRAY['active'::character varying, 'read'::character varying, 'dismissed'::character varying, 'expired'::character varying]::text[])", name: "chk_insights_status"+ end+create_table "invitations", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|t.string "email"t.string "role"@@ -2222,6 +2247,7 @@ ActiveRecord::Schema[7.2].define(version: 2026_06_28_200000) doadd_foreign_key "imports", "import_sessions", column: ["import_session_id", "family_id"], primary_key: ["id", "family_id"], name: "fk_imports_session_family", on_delete: :cascadeadd_foreign_key "indexa_capital_accounts", "indexa_capital_items"add_foreign_key "indexa_capital_items", "families"+ add_foreign_key "insights", "families"add_foreign_key "invitations", "families"add_foreign_key "invitations", "users", column: "inviter_id"add_foreign_key "kraken_accounts", "kraken_items"diff --git a/test/controllers/insights_controller_test.rb b/test/controllers/insights_controller_test.rbnew file mode 100644index 0000000000..90c8e06e05--- /dev/null+++ b/test/controllers/insights_controller_test.rb@@ -0,0 +1,100 @@+require "test_helper"++class InsightsControllerTest < ActionDispatch::IntegrationTest+ setup do+ sign_in @user = users(:family_admin)+ @insight = insights(:spending_anomaly_dining)+ ensure_tailwind_build+ end++ test "index renders visible insights and marks them read" do+ get insights_url++ assert_response :success+ assert_match CGI.escapeHTML(@insight.title), response.body+ assert @insight.reload.read?+ end++ test "turbo prefetch requests do not mark insights read" do+ get insights_url, headers: { "X-Sec-Purpose" => "prefetch" }++ assert_response :success+ assert @insight.reload.active?+ end++ test "dashboard renders the insights feed section with unread badges" do+ get root_url++ assert_response :success+ assert_select "#insights-feed", count: 1+ assert_select "#insights-feed span", text: I18n.t("insights.card.new")+ end++ test "insights feed leads the dashboard for users with a saved order that predates it" do+ @user.update!(preferences: (@user.preferences || {}).merge(+ "section_order" => %w[cashflow_sankey outflows_donut net_worth_chart balance_sheet]+ ))++ get root_url++ assert_response :success+ feed_position = response.body.index('data-section-key="insights_feed"')+ sankey_position = response.body.index('data-section-key="cashflow_sankey"')+ assert feed_position.present? && feed_position < sankey_position,+ "insights_feed should be prepended, not appended, for saved orders that predate it"+ end++ test "dismiss removes the insight from the feed and offers undo via turbo stream" do+ patch dismiss_insight_url(@insight), as: :turbo_stream++ assert_response :success+ assert_match "turbo-stream", response.body+ assert_match undismiss_insight_path(@insight), response.body+ assert @insight.reload.dismissed?+ end++ test "undismiss restores the insight as read and re-renders the list" do+ @insight.dismiss!++ patch undismiss_insight_url(@insight), as: :turbo_stream++ assert_response :success+ assert_match "insights-list", response.body+ assert_match CGI.escapeHTML(@insight.title), response.body+ assert @insight.reload.read?+ assert_nil @insight.dismissed_at+ end++ test "refresh swaps the button into a pending state via turbo stream" do+ assert_enqueued_with(job: GenerateInsightsJob, args: [ { family_id: @user.family_id } ]) do+ post refresh_insights_url, as: :turbo_stream+ end++ assert_response :success+ assert_match "insights-refresh", response.body+ assert_match CGI.escapeHTML(I18n.t("insights.refresh.checking")), response.body+ end++ test "cannot dismiss another family's insight" do+ other_insight = families(:empty).insights.create!(+ insight_type: "idle_cash",+ priority: "low",+ title: "Someone else's insight",+ body: "Body",+ dedup_key: "idle_cash:other:2026-07"+ )++ patch dismiss_insight_url(other_insight), as: :turbo_stream++ assert_response :not_found+ assert other_insight.reload.active?+ end++ test "refresh enqueues insight generation for the family" do+ assert_enqueued_with(job: GenerateInsightsJob, args: [ { family_id: @user.family_id } ]) do+ post refresh_insights_url+ end++ assert_redirected_to insights_path+ end+enddiff --git a/test/fixtures/insights.yml b/test/fixtures/insights.ymlnew file mode 100644index 0000000000..372f5bb3b4--- /dev/null+++ b/test/fixtures/insights.yml@@ -0,0 +1,32 @@+spending_anomaly_dining:+ family: dylan_family+ insight_type: spending_anomaly+ priority: medium+ status: active+ title: Food & Drink spending is up+ body: You've spent about 40% more on Food & Drink this month than your recent three-month average.+ metadata:+ category_id: food-and-drink+ direction: above+ deviation_bucket: 25+ currency: USD+ period_start: <%= Date.current.beginning_of_month %>+ period_end: <%= Date.current.end_of_month %>+ generated_at: <%= 1.day.ago %>+ dedup_key: <%= "spending_anomaly:food-and-drink:#{Date.current.strftime("%Y-%m")}" %>++cash_flow_warning:+ family: dylan_family+ insight_type: cash_flow_warning+ priority: high+ status: active+ title: Checking balance may run low+ body: Based on your upcoming bills and typical spending, your checking balance could drop to about $320 in the next 30 days.+ metadata:+ negative: false+ projected_low_bucket: 250+ currency: USD+ period_start: <%= Date.current %>+ period_end: <%= 30.days.from_now.to_date %>+ generated_at: <%= 1.day.ago %>+ dedup_key: <%= "cash_flow_warning:#{Date.current.strftime("%Y-%m")}" %>diff --git a/test/helpers/insights_helper_test.rb b/test/helpers/insights_helper_test.rbnew file mode 100644index 0000000000..84af796618--- /dev/null+++ b/test/helpers/insights_helper_test.rb@@ -0,0 +1,121 @@+require "test_helper"++class InsightsHelperTest < ActionView::TestCase+ test "positive types render success regardless of priority" do+ insight = build_insight("net_worth_milestone", priority: "high", metadata: { "milestone" => 500_000 })++ assert_equal :positive, insight_sentiment(insight)+ assert_equal "success", insight_icon_color(insight)+ end++ test "savings rate improvement is positive even at high priority" do+ insight = build_insight(+ "savings_rate_change",+ priority: "high",+ metadata: { "current_rate" => 32.5, "previous_rate" => 20.1 }+ )++ assert_equal :positive, insight_sentiment(insight)+ assert_equal "success", insight_icon_color(insight)+ end++ test "savings rate drop warns without going red" do+ insight = build_insight(+ "savings_rate_change",+ priority: "high",+ metadata: { "current_rate" => -5.4, "previous_rate" => 45.2 }+ )++ assert_equal :warning, insight_sentiment(insight)+ assert_equal "warning", insight_icon_color(insight)+ end++ test "spending anomaly direction decides sentiment" do+ above = build_insight("spending_anomaly", metadata: { "direction" => "above" })+ below = build_insight("spending_anomaly", metadata: { "direction" => "below" })++ assert_equal :warning, insight_sentiment(above)+ assert_equal :positive, insight_sentiment(below)+ end++ test "only a projected-negative balance renders destructive" do+ negative = build_insight("cash_flow_warning", priority: "high", metadata: { "negative" => true })+ low = build_insight("cash_flow_warning", priority: "medium", metadata: { "negative" => false })++ assert_equal "destructive", insight_icon_color(negative)+ assert_equal "warning", insight_icon_color(low)+ end++ test "informational types stay neutral" do+ %w[subscription_audit idle_cash].each do |type|+ assert_equal :neutral, insight_sentiment(build_insight(type))+ assert_equal "default", insight_icon_color(build_insight(type))+ end+ end++ test "rows written before the metadata shape change degrade safely" do+ stale = build_insight("cash_flow_warning", priority: "high", metadata: { "projected_low_amount" => 320.0 })++ assert_equal :warning, insight_sentiment(stale)+ end++ test "meta line shows the type and a month-aligned period as the month name" do+ insight = build_insight(+ "savings_rate_change",+ period_start: Date.new(Date.current.year, 6, 1),+ period_end: Date.new(Date.current.year, 6, 30)+ )++ assert_equal "Savings rate · June", insight_meta_line(insight)+ end++ test "meta line labels a forward-looking window as next N days" do+ insight = build_insight(+ "cash_flow_warning",+ period_start: Date.current,+ period_end: Date.current + 30+ )++ assert_equal "Cash flow · Next 30 days", insight_meta_line(insight)+ end++ test "meta line falls back to the subject when there is no period" do+ insight = build_insight("idle_cash", facts: { "account" => "Emergency fund" })++ assert_equal "Idle cash · Emergency fund", insight_meta_line(insight)+ end++ test "key figure comes from facts and hides for rows without them" do+ with_facts = build_insight("idle_cash", facts: { "balance" => "$28,400.00", "idle_days" => 60 })+ without_facts = build_insight("idle_cash")++ assert_equal "$28,400.00", insight_key_figure(with_facts).first+ assert_nil insight_key_figure(without_facts)+ end++ test "action link resolves the stored subject and disappears when it cannot" do+ account = families(:dylan_family).accounts.visible.first+ resolvable = build_insight("idle_cash", metadata: { "account_id" => account.id })+ dangling = build_insight("idle_cash", metadata: { "account_id" => SecureRandom.uuid })++ assert_equal account_path(account), insight_action(resolvable)[:href]+ assert_nil insight_action(dangling)+ end++ private+ def build_insight(insight_type, priority: "medium", metadata: {}, facts: {}, period_start: nil, period_end: nil)+ Insight.new(+ family: families(:dylan_family),+ insight_type: insight_type,+ priority: priority,+ status: "active",+ title: "t",+ body: "b",+ metadata: metadata,+ facts: facts,+ period_start: period_start,+ period_end: period_end,+ dedup_key: "#{insight_type}:test"+ )+ end+enddiff --git a/test/jobs/generate_insights_job_test.rb b/test/jobs/generate_insights_job_test.rbnew file mode 100644index 0000000000..f369670bf0--- /dev/null+++ b/test/jobs/generate_insights_job_test.rb@@ -0,0 +1,185 @@+require "test_helper"++class GenerateInsightsJobTest < ActiveJob::TestCase+ setup do+ @family = families(:dylan_family)+ end++ test "without args enqueues one job per family" do+ assert_enqueued_jobs Family.count, only: GenerateInsightsJob do+ GenerateInsightsJob.perform_now+ end+ end++ test "does nothing for an unknown family" do+ assert_nothing_raised do+ GenerateInsightsJob.perform_now(family_id: SecureRandom.uuid)+ end+ end++ test "does nothing for a family without accounts" do+ family = families(:empty)++ assert_no_difference "Insight.count" do+ GenerateInsightsJob.perform_now(family_id: family.id)+ end+ end++ test "runs all generators against real family data without raising" do+ assert_nothing_raised do+ GenerateInsightsJob.perform_now(family_id: @family.id)+ end+ end++ test "creates an active insight with a body from a generated insight" do+ stub_generated([ generated_insight ])++ assert_difference "@family.insights.count", 1 do+ GenerateInsightsJob.perform_now(family_id: @family.id)+ end++ insight = @family.insights.find_by(dedup_key: "idle_cash:test-account:2026-07")+ assert_equal "active", insight.status+ assert_equal "idle_cash", insight.insight_type+ assert insight.body.present?+ assert_equal 5000.0, insight.metadata["balance"]+ end++ test "re-running with unchanged numbers does not duplicate or rewrite" 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++ assert_no_difference "@family.insights.count" do+ GenerateInsightsJob.perform_now(family_id: @family.id)+ end++ assert_equal original_body, insight.reload.body+ end++ test "persists display facts and refreshes them without a body rewrite when metadata is unchanged" 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")+ assert_equal "$5000", insight.facts["balance"]+ original_body = insight.body+ insight.mark_read!++ stub_generated([ generated_insight(display_balance: 5040) ])+ GenerateInsightsJob.perform_now(family_id: @family.id)++ insight.reload+ assert_equal "$5040", insight.facts["balance"]+ assert_equal original_body, insight.body+ assert insight.read?+ end++ test "dismissed insight stays dismissed when numbers are unchanged" 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.dismiss!++ GenerateInsightsJob.perform_now(family_id: @family.id)++ assert insight.reload.dismissed?+ end++ test "dismissed insight reactivates when numbers change materially" 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.dismiss!++ stub_generated([ generated_insight(balance: 9000.0) ])+ GenerateInsightsJob.perform_now(family_id: @family.id)++ insight.reload+ assert insight.active?+ assert_equal 9000.0, insight.metadata["balance"]+ assert_nil insight.dismissed_at+ assert_nil insight.read_at+ end++ test "expires a visible insight whose condition cleared" do+ insight = insights(:cash_flow_warning)+ stub_generated([], succeeded_types: [ "cash_flow_warning" ])++ GenerateInsightsJob.perform_now(family_id: @family.id)++ assert insight.reload.expired?+ assert_not_includes Insight.visible, insight+ end++ test "does not expire insights whose generator failed" do+ insight = insights(:cash_flow_warning)+ stub_generated([], succeeded_types: [])++ GenerateInsightsJob.perform_now(family_id: @family.id)++ assert insight.reload.active?+ end++ test "does not touch dismissed insights when their condition clears" do+ insight = insights(:cash_flow_warning)+ insight.dismiss!+ stub_generated([], succeeded_types: [ "cash_flow_warning" ])++ GenerateInsightsJob.perform_now(family_id: @family.id)++ assert insight.reload.dismissed?+ end++ test "expired insight reactivates without a body rewrite when the condition returns unchanged" 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([], succeeded_types: [ "idle_cash" ])+ GenerateInsightsJob.perform_now(family_id: @family.id)+ assert insight.reload.expired?++ stub_generated([ generated_insight ])+ GenerateInsightsJob.perform_now(family_id: @family.id)++ insight.reload+ assert insight.active?+ assert_equal original_body, insight.body+ assert_nil insight.read_at+ end++ private+ def stub_generated(generated_insights, succeeded_types: nil)+ result = Insight::GeneratorRegistry::Result.new(+ insights: generated_insights,+ succeeded_types: succeeded_types || generated_insights.map(&:insight_type).uniq+ )+ Insight::GeneratorRegistry.any_instance.stubs(:generate_all).returns(result)+ end++ # 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)+ Insight::Generator::GeneratedInsight.new(+ insight_type: "idle_cash",+ priority: "low",+ title: "Idle cash in Test Checking",+ template_key: "idle_cash",+ facts: { account: "Test Checking", balance: "$#{(display_balance || balance).to_i}", idle_days: 60 },+ metadata: { account_id: "test-account", balance: balance },+ currency: "USD",+ period_start: nil,+ period_end: nil,+ dedup_key: "idle_cash:test-account:2026-07"+ )+ end+enddiff --git a/test/models/insight/body_writer_test.rb b/test/models/insight/body_writer_test.rbnew file mode 100644index 0000000000..20c6390ffb--- /dev/null+++ b/test/models/insight/body_writer_test.rb@@ -0,0 +1,98 @@+require "test_helper"+require "ostruct"++class Insight::BodyWriterTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ end++ test "writes the template body when nobody in the family has AI enabled" do+ @family.users.update_all(ai_enabled: false)+ Provider::Registry.expects(:preferred_llm_provider).never++ body = Insight::BodyWriter.new(@family).write(generated_insight)++ assert_equal I18n.t("insights.templates.idle_cash", **generated_insight.facts.symbolize_keys), body+ end++ test "uses LLM prose when a user has opted in and a provider is configured" do+ Provider::Registry.stubs(:preferred_llm_provider).returns(FakeLlmProvider.new("Narrated body."))++ body = Insight::BodyWriter.new(@family).write(generated_insight)++ assert_equal "Narrated body.", body+ end++ test "falls back to the template and captures a debug log when the LLM call fails" do+ provider = FakeLlmProvider.new("unused")+ provider.stubs(:chat_response).raises(StandardError.new("boom"))+ Provider::Registry.stubs(:preferred_llm_provider).returns(provider)++ body = nil+ assert_difference "DebugLogEntry.count", 1 do+ body = Insight::BodyWriter.new(@family).write(generated_insight)+ end++ assert_equal I18n.t("insights.templates.idle_cash", **generated_insight.facts.symbolize_keys), body+ end++ test "every template key interpolates with its generator's facts" do+ TEMPLATE_FACTS.each do |template_key, facts|+ body = I18n.t!("insights.templates.#{template_key}", **facts)++ assert body.present?, "insights.templates.#{template_key} produced a blank body"+ 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+ # instead of shipping "translation missing" as a stored body in production.+ TEMPLATE_FACTS = {+ "spending_anomaly.above" => { category: "Food & Drink", deviation_pct: 38, projected_spend: "$612.00", baseline_spend: "$443.00" },+ "spending_anomaly.below" => { category: "Food & Drink", deviation_pct: 30, projected_spend: "$310.00", baseline_spend: "$443.00" },+ "cash_flow_warning.low" => { projected_low: "$320.00", projected_low_date: "Jul 28, 2026", current_balance: "$1,200.00", horizon_days: 30 },+ "cash_flow_warning.negative" => { projected_low: "-$412.00", projected_low_date: "Jul 28, 2026", current_balance: "$800.00", horizon_days: 30 },+ "net_worth_milestone" => { milestone: "$500,000", net_worth: "$878,578.56" },+ "subscription_audit" => { name: "Netflix", amount: "$15.49", days_overdue: 48, expected_on: "May 24, 2026" },+ "savings_rate_change.up" => { month: "June", current_rate: 32.5, previous_rate: 20.1, change_pp: 12.4 },+ "savings_rate_change.down" => { month: "June", current_rate: "12.1", previous_rate: "45.2", change_pp: 33.1 },+ "savings_rate_change.down_negative" => { month: "June", current_rate: "−5.4", previous_rate: "45.2", change_pp: 50.6 },+ "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 }+ }.freeze++ class FakeLlmProvider+ def self.effective_model+ "fake-model"+ end++ def initialize(body)+ @body = body+ end++ def chat_response(*, **)+ OpenStruct.new(+ success?: true,+ data: OpenStruct.new(messages: [ OpenStruct.new(id: "1", output_text: @body) ])+ )+ end+ end++ def generated_insight+ @generated_insight ||= Insight::Generator::GeneratedInsight.new(+ insight_type: "idle_cash",+ priority: "low",+ title: "Idle cash in Emergency fund",+ template_key: "idle_cash",+ facts: { account: "Emergency fund", balance: "$28,400.00", idle_days: 60 },+ metadata: { account_id: "acct", balance: 28_400.0 },+ currency: "USD",+ period_start: nil,+ period_end: nil,+ dedup_key: "idle_cash:acct:2026-07"+ )+ end+enddiff --git a/test/models/insight_test.rb b/test/models/insight_test.rbnew file mode 100644index 0000000000..b7fc32d3d7--- /dev/null+++ b/test/models/insight_test.rb@@ -0,0 +1,90 @@+require "test_helper"++class InsightTest < ActiveSupport::TestCase+ setup do+ @insight = insights(:spending_anomaly_dining)+ end++ test "mark_read! transitions active insight and stamps read_at" do+ assert @insight.active?++ @insight.mark_read!++ assert @insight.reload.read?+ assert @insight.read_at.present?+ end++ test "mark_read! does not touch dismissed insights" do+ @insight.dismiss!++ @insight.mark_read!++ assert @insight.reload.dismissed?+ assert_nil @insight.read_at+ end++ test "dismiss! removes insight from visible scope" do+ assert_includes Insight.visible, @insight++ @insight.dismiss!++ assert_not_includes Insight.visible, @insight+ assert @insight.dismissed_at.present?+ end++ test "undismiss! restores a dismissed insight as read, not new" do+ @insight.dismiss!++ @insight.undismiss!++ assert @insight.reload.read?+ assert_nil @insight.dismissed_at+ assert @insight.read_at.present?+ assert_includes Insight.visible, @insight+ end++ test "duplicate dedup_key within a family is rejected" do+ assert_raises ActiveRecord::RecordInvalid do+ @insight.family.insights.create!(+ insight_type: @insight.insight_type,+ priority: "medium",+ title: "Duplicate",+ body: "Duplicate body",+ dedup_key: @insight.dedup_key+ )+ end+ end++ test "same dedup_key is allowed across families" do+ other_family = families(:empty)++ assert_nothing_raised do+ other_family.insights.create!(+ insight_type: @insight.insight_type,+ priority: "medium",+ title: "Same key, other family",+ body: "Body",+ dedup_key: @insight.dedup_key+ )+ end+ end++ test "ordered puts high priority first, then most recent" do+ high = insights(:cash_flow_warning)++ assert_equal high, Insight.ordered.first+ end++ test "insight_type must be a known type" do+ insight = Insight.new(+ family: families(:empty),+ insight_type: "bogus",+ title: "t",+ body: "b",+ dedup_key: "bogus:key"+ )++ assert_not insight.valid?+ assert insight.errors[:insight_type].any?+ end+enddiff --git a/test/models/user_test.rb b/test/models/user_test.rbindex 60825eff9f..2ab21ffec4 100644--- a/test/models/user_test.rb+++ b/test/models/user_test.rb@@ -557,7 +557,7 @@ class UserTest < ActiveSupport::TestCase"Should return false when collapsed_sections key is missing"# dashboard_section_order should return default order when key is missing- assert_equal %w[cashflow_sankey outflows_donut net_worth_chart balance_sheet],+ assert_equal %w[insights_feed cashflow_sankey outflows_donut net_worth_chart balance_sheet],@user.dashboard_section_order,"Should return default order when section_order key is missing"