The personal finance app for everyone (by everyone)
Ruby
fix(insights): compute shared insights from accounts every member can see (#4206)
GFR1cd94e66182e
diff --git a/app/jobs/generate_insights_job.rb b/app/jobs/generate_insights_job.rbindex ecb7ad489f..590f4e1df1 100644--- a/app/jobs/generate_insights_job.rb+++ b/app/jobs/generate_insights_job.rb@@ -1,4 +1,7 @@class GenerateInsightsJob < ApplicationJob+ # Metadata that says which accounts an insight is about, not what it found.+ ACCOUNT_SCOPE_KEYS = %w[accounts_digest account_id].freeze+queue_as :scheduledsidekiq_options lock: :until_executed, on_conflict: :log@@ -115,6 +118,15 @@ class GenerateInsightsJob < ApplicationJobgenerated_at: Time.current,dedup_key: generated.dedup_key)+ elsif !existing.expired? && existing.metadata != metadata &&+ existing.metadata.except(*ACCOUNT_SCOPE_KEYS) == metadata.except(*ACCOUNT_SCOPE_KEYS)+ # Only the accounts behind the insight changed (a share granted or+ # revoked, or a row written before these keys existed). The prose+ # may quote figures from the old set, so it is rewritten, but the+ # signal itself did not change: read and dismissed state stay.+ existing.update!(title: generated.title, body: writer.write(generated), metadata: metadata,+ facts: facts, generated_at: Time.current)+ nilelsif 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.diff --git a/app/models/balance_sheet/net_worth_series_builder.rb b/app/models/balance_sheet/net_worth_series_builder.rbindex b987d80660..f303041918 100644--- a/app/models/balance_sheet/net_worth_series_builder.rb+++ b/app/models/balance_sheet/net_worth_series_builder.rb@@ -1,7 +1,11 @@class BalanceSheet::NetWorthSeriesBuilder- def initialize(family, user: nil)+ # `accounts:` (an Account relation) narrows the series to a subset of what+ # the user (or, without one, the family) would otherwise get, e.g. the+ # insights feed's accounts every member may see.+ def initialize(family, user: nil, accounts: nil)@family = family@user = user+ @accounts = accountsenddef net_worth_series(period: Period.last_30_days)@@ -19,10 +23,14 @@ class BalanceSheet::NetWorthSeriesBuilderendprivate- attr_reader :family, :user+ attr_reader :family, :user, :accountsdef historical_accounts- @historical_accounts ||= historical_account_scope.relation.to_a+ @historical_accounts ||= begin+ scope = historical_account_scope.relation+ scope = scope.where(id: accounts.select(:id)) if accounts+ scope.to_a+ endenddef historical_account_ids@@ -51,6 +59,7 @@ class BalanceSheet::NetWorthSeriesBuilderExchangeRate.maximum(:updated_at)&.to_i,user&.id,shares_version,+ accounts_digest,period.start_date,period.end_date].compact.join("_")@@ -60,4 +69,12 @@ class BalanceSheet::NetWorthSeriesBuilderinvalidate_on_data_updates: true)end++ # A narrowed series must not share a cache entry with the full one, and a+ # share granted or revoked changes the set, so the key carries the ids.+ def accounts_digest+ return nil unless accounts++ Digest::MD5.hexdigest(historical_account_ids.sort.join(","))+ endenddiff --git a/app/models/insight.rb b/app/models/insight.rbindex ffff769550..3c0340dd6f 100644--- a/app/models/insight.rb+++ b/app/models/insight.rb@@ -65,6 +65,27 @@ class Insight < ApplicationRecordENDSQLwhere("NOT (insights.metadata ? 'account_id')").or(where(shared_account.arel.exists))+ .about_shared_recurring_transactions+ }++ # A recurring series can move to another account after its insight was+ # written, so the stored account_id may be stale. An insight that names a+ # series (metadata recurring_transaction_id) also checks the series' current+ # account: it shows only while that series exists and has no account or one+ # every active member can see.+ scope :about_shared_recurring_transactions, -> {+ shared_account = Account.visible.accessible_by_all_active_members+ .where("accounts.id = recurring_transactions.account_id")+ current_series = RecurringTransaction+ .where("recurring_transactions.family_id = insights.family_id")+ .where(<<~SQL.squish)+ recurring_transactions.id = CASE+ WHEN insights.metadata->>'recurring_transaction_id' ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'+ THEN (insights.metadata->>'recurring_transaction_id')::uuid+ END+ SQL+ .where("recurring_transactions.account_id IS NULL OR EXISTS (#{shared_account.to_sql})")+ where("NOT (insights.metadata ? 'recurring_transaction_id')").or(where(current_series.arel.exists))}scope :ordered, -> {diff --git a/app/models/insight/generator.rb b/app/models/insight/generator.rbindex fe92081c13..61c89deeae 100644--- a/app/models/insight/generator.rb+++ b/app/models/insight/generator.rb@@ -44,12 +44,42 @@ class Insight::Generatorprivateattr_reader :family+ # The feed is one list shared by the whole family, so every figure in it is+ # computed only from accounts each active member may open. Without this a+ # member's private account would feed totals that everyone reads.+ #+ # The ids are read once per run, so every figure and the digest describe+ # the same account set even if access changes while the generator runs.+ def shared_accounts+ @shared_accounts ||= family.accounts.where(id: shared_account_ids)+ end++ def shared_account_ids+ @shared_account_ids ||= family.accounts.accessible_by_all_active_members.order(:id).pluck(:id)+ end++ # The account scope is passed explicitly: IncomeStatement falls back to+ # `Current.user`, which is nil in the nightly job and would mean "every+ # account in the family". Status, report and tax filters stay its own.def income_statement- @income_statement ||= IncomeStatement.new(family)+ @income_statement ||= IncomeStatement.new(family, accounts: shared_accounts)+ end++ # Totals have no single account that Insight.about_shared_accounts could+ # recheck on read, so an aggregate insight carries the account set it was+ # computed from. When a share is granted or revoked the digest changes and+ # the job rewrites the body (see GenerateInsightsJob#upsert_insights), so+ # prose written from the old set does not outlive it.+ def shared_accounts_digest+ @shared_accounts_digest ||= Digest::SHA256.hexdigest(shared_account_ids.join(","))end- def balance_sheet- @balance_sheet ||= BalanceSheet.new(family)+ # Recurring series follow the same rule, matching+ # RecurringTransaction.accessible_by: a series without an account (legacy+ # rows) belongs to nobody in particular and stays in.+ def shared_recurring_transactions+ RecurringTransaction.where(account_id: nil)+ .or(RecurringTransaction.where(account_id: shared_accounts.select(:id)))enddef build_insight(insight_type:, priority:, title:, template_key:, facts:, dedup_key:, metadata:, period: nil)diff --git a/app/models/insight/generators/budget_insight_generator.rb b/app/models/insight/generators/budget_insight_generator.rbindex 9e2b173f52..ba9be35767 100644--- a/app/models/insight/generators/budget_insight_generator.rb+++ b/app/models/insight/generators/budget_insight_generator.rb@@ -12,6 +12,9 @@ class Insight::Generators::BudgetInsightGenerator < Insight::Generatordef generatebudget = current_budgetreturn [] unless budget&.initialized?+ # With no shared account the budget can count, its spending reads as zero+ # and would be reported as "on track" while members spend privately.+ return [] unless countable_shared_accounts.exists?parent_categories = budget.budget_categories.reject(&:subcategory?)over = parent_categories.select(&:over_budget_with_budget?)@@ -27,11 +30,25 @@ class Insight::Generators::BudgetInsightGenerator < Insight::Generatorendprivate+ # The same filters IncomeStatement applies to totals (visible, included in+ # reports, not tax-advantaged), so a shared account that is disabled or+ # excluded from reports does not count as something the budget can read.+ def countable_shared_accounts+ income_statement.eligible_accounts.where(id: shared_accounts.select(:id))+ end++ # The household budget only: a personal budget is visible to its owner and+ # whoever they shared it with, not to the whole feed. Its spending is read+ # from the accounts every member may see; left alone, the budget would+ # fall back to `Current.user` (nil here) and count every account.def current_budget- family.budgets+ budget = family.budgets+ .where(user_id: nil).includes(budget_categories: :category).where("start_date <= ? AND end_date >= ?", Date.current, Date.current).first+ budget&.income_statement_accounts = shared_accounts+ budgetenddef at_risk_insight(budget, over, near)@@ -53,7 +70,8 @@ class Insight::Generators::BudgetInsightGenerator < Insight::Generatormetadata: {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+ budget_spent_pct_bucket: (round(budget.percent_of_budget_spent, 0).to_i / 10) * 10,+ accounts_digest: shared_accounts_digest},period: budget.period,dedup_key: "budget_at_risk:#{month_token(budget.start_date)}"@@ -74,7 +92,8 @@ class Insight::Generators::BudgetInsightGenerator < Insight::Generator# 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+ budget_spent_pct_bucket: (round(budget.percent_of_budget_spent, 0).to_i / 10) * 10,+ accounts_digest: shared_accounts_digest},period: budget.period,dedup_key: "budget_on_track:#{month_token(budget.start_date)}"diff --git a/app/models/insight/generators/cash_flow_warning_generator.rb b/app/models/insight/generators/cash_flow_warning_generator.rbindex 5c2c7ff064..64c374ed2c 100644--- a/app/models/insight/generators/cash_flow_warning_generator.rb+++ b/app/models/insight/generators/cash_flow_warning_generator.rb@@ -65,7 +65,8 @@ class Insight::Generators::CashFlowWarningGenerator < Insight::Generator# 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+ projected_low_bucket: (round(low_point, 0).to_i / 250) * 250,+ accounts_digest: shared_accounts_digest},period: Period.custom(start_date: Date.current, end_date: Date.current + HORIZON_DAYS),dedup_key: "cash_flow_warning:#{month_token}"@@ -75,7 +76,7 @@ class Insight::Generators::CashFlowWarningGenerator < Insight::Generatorprivatedef cash_accounts- family.accounts.visible.where(accountable_type: "Depository", currency: family.currency)+ shared_accounts.visible.where(accountable_type: "Depository", currency: family.currency)end# Projected occurrences of known recurring transactions within the horizon.@@ -103,6 +104,7 @@ class Insight::Generators::CashFlowWarningGenerator < Insight::Generator.open_status.joins(:recurring_transaction).where(recurring_transactions: { status: :active, destination_account_id: nil })+ .merge(shared_recurring_transactions).where("recurring_transactions.amount > 0").where(currency: family.currency).where(due_on: Date.current..(Date.current + HORIZON_DAYS))diff --git a/app/models/insight/generators/net_worth_milestone_generator.rb b/app/models/insight/generators/net_worth_milestone_generator.rbindex 579c38f790..4cd4c452a3 100644--- a/app/models/insight/generators/net_worth_milestone_generator.rb+++ b/app/models/insight/generators/net_worth_milestone_generator.rb@@ -50,7 +50,8 @@ class Insight::Generators::NetWorthMilestoneGenerator < Insight::Generator# 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+ milestone: milestone,+ accounts_digest: shared_accounts_digest},period: window,dedup_key: "net_worth_milestone:#{milestone}"@@ -63,7 +64,8 @@ class Insight::Generators::NetWorthMilestoneGenerator < Insight::Generator# of the window can still be checked against the days that preceded it.def net_worth_history(window)period = Period.custom(start_date: window.start_date - QUIET_PERIOD, end_date: window.end_date)- balance_sheet.net_worth_series(period: period).values.map do |value|+ BalanceSheet::NetWorthSeriesBuilder.new(family, accounts: shared_accounts)+ .net_worth_series(period: period).values.map do |value|Point.new(date: value.date, amount: money_amount(value.value))endenddiff --git a/app/models/insight/generators/savings_rate_change_generator.rb b/app/models/insight/generators/savings_rate_change_generator.rbindex 11f606c9ca..d02fbd8b8b 100644--- a/app/models/insight/generators/savings_rate_change_generator.rb+++ b/app/models/insight/generators/savings_rate_change_generator.rb@@ -44,7 +44,8 @@ class Insight::Generators::SavingsRateChangeGenerator < Insight::Generator},metadata: {current_rate: round(current_rate, 1),- previous_rate: round(previous_rate, 1)+ previous_rate: round(previous_rate, 1),+ accounts_digest: shared_accounts_digest},period: last_month,dedup_key: "savings_rate_change:#{month_token(last_month.start_date)}"diff --git a/app/models/insight/generators/spending_anomaly_generator.rb b/app/models/insight/generators/spending_anomaly_generator.rbindex df7e4c8b45..3286c1ea3b 100644--- a/app/models/insight/generators/spending_anomaly_generator.rb+++ b/app/models/insight/generators/spending_anomaly_generator.rb@@ -66,7 +66,8 @@ class Insight::Generators::SpendingAnomalyGenerator < Insight::Generatormetadata: {category_id: anomaly[:category_id],direction: direction,- deviation_bucket: (round(anomaly[:deviation_pct].abs, 0).to_i / 25) * 25+ deviation_bucket: (round(anomaly[:deviation_pct].abs, 0).to_i / 25) * 25,+ accounts_digest: shared_accounts_digest},period: period,dedup_key: "spending_anomaly:#{anomaly[:category_id]}:#{month_token(period.start_date)}"diff --git a/app/models/insight/generators/subscription_audit_generator.rb b/app/models/insight/generators/subscription_audit_generator.rbindex d29c2c507c..c99792fa57 100644--- a/app/models/insight/generators/subscription_audit_generator.rb+++ b/app/models/insight/generators/subscription_audit_generator.rb@@ -31,11 +31,15 @@ class Insight::Generators::SubscriptionAuditGenerator < Insight::Generator},# days_overdue is deliberately left out: it changes every night, and# metadata drift would resurrect insights the user already dismissed.+ # account_id lets the feed hide the row once the account stops being+ # shared (Insight.about_shared_accounts); a series without an account+ # leaves the key out, since an explicit null would always hide it.metadata: {recurring_transaction_id: recurring.id,+ account_id: recurring.account_id,amount: round(occurrence.resolved_expected_amount, 2),expected_on: occurrence.due_on.iso8601- },+ }.compact,dedup_key: "subscription_audit:#{recurring.id}")end@@ -53,11 +57,14 @@ class Insight::Generators::SubscriptionAuditGenerator < Insight::Generator.open_status.joins(:recurring_transaction).where(recurring_transactions: { status: :active, destination_account_id: nil })+ .merge(shared_recurring_transactions).where("recurring_transactions.amount > 0").where("due_on < ?", Date.current).includes(recurring_transaction: [ :merchant, :recurrence_rules ]).to_a+ candidates -= paid_from_private_accounts(candidates)+stale = candidates.select do |occurrence|cycle_days = 365.25 / occurrence.recurring_transaction.schedule.occurrences_per_year(Date.current - occurrence.due_on).to_i >= [ cycle_days.round, 1 ].max@@ -69,4 +76,28 @@ class Insight::Generators::SubscriptionAuditGenerator < Insight::Generator.sort_by(&:due_on).first(MAX_INSIGHTS)end++ # A series without an account can match payments from any family account.+ # Under the "last" and "average" strategies its expected amount comes from+ # those payments, so the audit would reveal what a private account paid.+ # Such series are skipped while any of their payments sits in an account+ # not every member can see; a fixed amount reveals no payment and stays.+ def paid_from_private_accounts(candidates)+ at_risk = candidates.select do |occurrence|+ occurrence.expected_amount.blank? &&+ occurrence.recurring_transaction.account_id.nil? &&+ !occurrence.recurring_transaction.amount_fixed?+ end+ return [] if at_risk.empty?++ private_series_ids = RecurringAllocation.confirmed+ .joins(:recurring_occurrence, :entry)+ .where(recurring_occurrences: { recurring_transaction_id: at_risk.map(&:recurring_transaction_id).uniq })+ .where.not(entries: { account_id: shared_account_ids })+ .distinct+ .pluck("recurring_occurrences.recurring_transaction_id")+ .to_set++ at_risk.select { |occurrence| private_series_ids.include?(occurrence.recurring_transaction_id) }+ endenddiff --git a/test/controllers/settings/hostings_controller_test.rb b/test/controllers/settings/hostings_controller_test.rbindex bef7e2e299..32875066d0 100644--- a/test/controllers/settings/hostings_controller_test.rb+++ b/test/controllers/settings/hostings_controller_test.rb@@ -1540,32 +1540,35 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTestSetting.tinkoff_invest_api_key = nilend+ # The cron job lives under one global key in the shared Redis, so these+ # tests stub Sidekiq::Cron instead: parallel workers creating and deleting+ # the real job made them fail at random.test "can update market data sync settings when self hosting is enabled" dowith_self_hosting do+ Sidekiq::Cron::Job.expects(:create)+ .with(has_entries(name: MarketDataScheduler::JOB_NAME, class: "ImportMarketDataJob", cron: regexp_matches(/\A30 18 /)))+ .returns(OpenStruct.new(valid?: true))+patch settings_hosting_url, params: { setting: { market_data_sync_enabled: "1", market_data_sync_time: "18:30" } }assert_redirected_to settings_hosting_urlassert Setting.market_data_sync_enabledassert_equal "18:30", Setting.market_data_sync_time-- job = Sidekiq::Cron::Job.find(MarketDataScheduler::JOB_NAME)- assert job, "Expected the market data cron job to be (re)created"- assert_equal "ImportMarketDataJob", job.klassend- ensure- Sidekiq::Cron::Job.find(MarketDataScheduler::JOB_NAME)&.destroyendtest "disabling market data sync removes its cron job" dowith_self_hosting do+ Sidekiq::Cron::Job.expects(:create)+ .with(has_entries(name: MarketDataScheduler::JOB_NAME))+ .returns(OpenStruct.new(valid?: true))patch settings_hosting_url, params: { setting: { market_data_sync_enabled: "1" } }- assert Sidekiq::Cron::Job.find(MarketDataScheduler::JOB_NAME)+ job = mock("cron job")+ job.expects(:destroy)+ Sidekiq::Cron::Job.expects(:find).with(MarketDataScheduler::JOB_NAME).returns(job)patch settings_hosting_url, params: { setting: { market_data_sync_enabled: "0" } }- refute Sidekiq::Cron::Job.find(MarketDataScheduler::JOB_NAME)end- ensure- Sidekiq::Cron::Job.find(MarketDataScheduler::JOB_NAME)&.destroyendtest "rejects an invalid market data sync time" do@@ -1582,14 +1585,13 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTesttest "still applies market_data_sync_enabled when market_data_sync_time in the same request is invalid" dowith_self_hosting doSetting.market_data_sync_enabled = false+ Sidekiq::Cron::Job.stubs(:create).returns(OpenStruct.new(valid?: true))patch settings_hosting_url, params: { setting: { market_data_sync_enabled: "1", market_data_sync_time: "not-a-time" } }assert_redirected_to settings_hosting_pathassert Setting.market_data_sync_enabled, "enabled flag from the same submission should not be dropped by the invalid time"end- ensure- Sidekiq::Cron::Job.find(MarketDataScheduler::JOB_NAME)&.destroyendtest "logs a failed market data schedule sync to the debug log" dodiff --git a/test/jobs/generate_insights_job_test.rb b/test/jobs/generate_insights_job_test.rbindex fe8a1e08cb..6bc16e3249 100644--- a/test/jobs/generate_insights_job_test.rb+++ b/test/jobs/generate_insights_job_test.rb@@ -242,6 +242,43 @@ class GenerateInsightsJobTest < ActiveJob::TestCaseassert_nil insight.read_atend+ # An aggregate carries the account set it was computed from. A share change+ # (or a row stored before the digest existed) rewrites prose that may quote+ # figures from the old set, without resurfacing what the user put away.+ test "a changed account set rewrites the body but keeps acknowledged state" 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.acknowledge!++ rescoped = generated_insight(display_balance: 3000)+ stub_generated([ rescoped.with(metadata: rescoped.metadata.merge(accounts_digest: "new-set")) ])+ GenerateInsightsJob.perform_now(family_id: @family.id)++ insight.reload+ assert_not_equal original_body, insight.body+ assert_includes insight.body, "$3000"+ assert_equal "new-set", insight.metadata["accounts_digest"]+ assert insight.acknowledged?+ end++ test "adding the account an insight is about keeps acknowledged state" do+ stub_generated([ generated_insight.with(metadata: generated_insight.metadata.except(:account_id)) ])+ GenerateInsightsJob.perform_now(family_id: @family.id)++ insight = @family.insights.find_by(dedup_key: "idle_cash:test-account:2026-07")+ insight.acknowledge!++ stub_generated([ generated_insight ])+ GenerateInsightsJob.perform_now(family_id: @family.id)++ insight.reload+ assert_equal accounts(:depository).id, insight.metadata["account_id"]+ assert insight.acknowledged?+ end+test "expires a visible insight whose condition cleared" doinsight = insights(:cash_flow_warning)stub_generated([], succeeded_types: [ "cash_flow_warning" ])diff --git a/test/models/insight/generator_test.rb b/test/models/insight/generator_test.rbnew file mode 100644index 0000000000..dcc86e7e27--- /dev/null+++ b/test/models/insight/generator_test.rb@@ -0,0 +1,32 @@+require "test_helper"++class Insight::GeneratorTest < ActiveSupport::TestCase+ # Exposes the shared-account helpers the way a generator uses them: figures+ # first, the digest for the metadata afterwards.+ class ProbeGenerator < Insight::Generator+ def figure_account_ids+ shared_accounts.pluck(:id)+ end++ def digest+ shared_accounts_digest+ end+ end++ setup do+ @family = families(:dylan_family)+ @generator = ProbeGenerator.new(@family)+ end++ test "the digest and later figures use the account set the first figures saw" do+ first_ids = @generator.figure_account_ids+ assert_not_includes first_ids, accounts(:connected).id++ # Access changes mid-run: with the only other member inactive, the private+ # account becomes visible to every active member.+ users(:family_member).update_columns(active: false)++ assert_equal first_ids.sort, @generator.figure_account_ids.sort+ assert_equal Digest::SHA256.hexdigest(first_ids.sort.join(",")), @generator.digest+ end+enddiff --git a/test/models/insight/generators/budget_insight_generator_test.rb b/test/models/insight/generators/budget_insight_generator_test.rbnew file mode 100644index 0000000000..5cd13e7d27--- /dev/null+++ b/test/models/insight/generators/budget_insight_generator_test.rb@@ -0,0 +1,86 @@+require "test_helper"++class Insight::Generators::BudgetInsightGeneratorTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @family = families(:dylan_family)+ @budget = budgets(:one)+ @category = @family.categories.create!(name: "Budget Insight Cat", color: "#101010", lucide_icon: "circle")+ end++ # 95 of 100 spent would be "near the limit", but the spend sits on+ # `connected`, private to family_admin. The shared feed must not report it.+ test "spending on an account private to one member does not put the budget at risk" do+ budget_category(@budget)+ create_transaction(category: @category, amount: 95, account: accounts(:connected), date: Date.current)++ assert_not_includes generated_types, "budget_at_risk"+ end++ test "spending on a shared account still puts the budget at risk" do+ budget_category(@budget)+ create_transaction(category: @category, amount: 95, date: Date.current)++ assert_includes generated_types, "budget_at_risk"+ end++ # With every account private, nothing is counted, so "on track" would only+ # mean that no shared spending exists.+ test "no budget insight when no account is visible to every member" do+ AccountShare.where(account: @family.accounts).delete_all+ budget_category(@budget)++ travel_to @budget.end_date do+ assert_empty generated_types+ end+ end++ # Shared but excluded from reports: IncomeStatement does not count it, so+ # the budget would again read zero spending as "on track".+ test "no budget insight when the only shared accounts are excluded from reports" do+ @family.accounts.accessible_by_all_active_members.update_all(exclude_from_reports: true)+ budget_category(@budget)++ travel_to @budget.end_date do+ assert_empty generated_types+ end+ end++ test "revoking a share changes the account digest of the insight" do+ budget_category(@budget)+ create_transaction(category: @category, amount: 95, date: Date.current)+ before = generated_digest++ account_shares(:credit_card_shared_with_member).destroy!++ assert_not_equal before, generated_digest+ end++ # A personal budget is visible to its owner and whoever they shared it with,+ # never to the whole family, so it must not reach the shared feed.+ test "a personal budget is not reported" do+ @budget.destroy!+ personal = @family.budgets.create!(+ user: users(:family_admin), start_date: Date.current.beginning_of_month,+ end_date: Date.current.end_of_month, budgeted_spending: 100, expected_income: 0, currency: "USD"+ )+ budget_category(personal)+ create_transaction(category: @category, amount: 95, date: Date.current)++ assert_empty generated_types+ end++ private+ def budget_category(budget)+ budget.budget_categories.create!(category: @category, budgeted_spending: 100, currency: "USD")+ end++ def generated_digest+ Insight::Generators::BudgetInsightGenerator.new(@family).generate.first.metadata[:accounts_digest]+ end++ def generated_types+ Insight::Generators::BudgetInsightGenerator.new(@family).generate.map(&:insight_type)+ end+enddiff --git a/test/models/insight/generators/cash_flow_warning_generator_test.rb b/test/models/insight/generators/cash_flow_warning_generator_test.rbindex 3dfb7228a3..bf23ca5116 100644--- a/test/models/insight/generators/cash_flow_warning_generator_test.rb+++ b/test/models/insight/generators/cash_flow_warning_generator_test.rb@@ -41,4 +41,40 @@ class Insight::Generators::CashFlowWarningGeneratorTest < ActiveSupport::TestCasassert_equal [ 60, 100, 100 ], entries.sort_by(&:date).map(&:amount).map(&:to_i),"the partially paid occurrence contributes only its remainder"end++ # The feed is shared by the whole family: `connected` is private to+ # family_admin, so its balance must not cover the shared projection.+ test "a private cash account does not feed the projected balance" do+ accounts(:depository).update_columns(balance: 100)+ accounts(:connected).update_columns(balance: 50_000)++ insights = Insight::Generators::CashFlowWarningGenerator.new(@family).generate++ assert_equal 1, insights.size+ assert_equal Money.new(100, "USD").format, insights.first.facts[:current_balance]+ end++ test "bills paid from a private account are left out of the projection" do+ private_series = @family.recurring_transactions.create!(+ name: "Private Gym", account: accounts(:connected), amount: 70, currency: "USD",+ expected_day_of_month: 15, last_occurrence_date: Date.current,+ next_expected_date: 1.month.from_now.to_date, status: "active", manual: true+ )+ private_series.recurring_occurrences.delete_all+ private_series.recurring_occurrences.create!(+ family: @family, original_due_on: Date.current + 2, due_on: Date.current + 2, currency: "USD"+ )++ entries = Insight::Generators::CashFlowWarningGenerator.new(@family).send(:upcoming_recurring_entries)++ assert_equal [ 60, 100, 100 ], entries.map(&:amount).map(&:to_i).sort+ end++ test "an inactive member does not hide an account from the projection" do+ users(:family_member).update_columns(active: false)+ accounts(:depository).update_columns(balance: 100)+ accounts(:connected).update_columns(balance: 50_000)++ assert_empty Insight::Generators::CashFlowWarningGenerator.new(@family).generate+ endenddiff --git a/test/models/insight/generators/net_worth_milestone_generator_test.rb b/test/models/insight/generators/net_worth_milestone_generator_test.rbindex 39fb2b4d27..62086ca3c8 100644--- a/test/models/insight/generators/net_worth_milestone_generator_test.rb+++ b/test/models/insight/generators/net_worth_milestone_generator_test.rb@@ -63,7 +63,31 @@ class Insight::Generators::NetWorthMilestoneGeneratorTest < ActiveSupport::TestCassert_empty dedup_keysend++ test "a private account does not push the shared net worth over a milestone" do+ shared_and_private_balances++ assert_empty dedup_keys+ end++ test "counts every account once the only other member is inactive" do+ shared_and_private_balances+ users(:family_member).update_columns(active: false)++ assert_equal [ "net_worth_milestone:10000" ], dedup_keys+ end+private+ # `depository` is shared with family_member; `connected` is private to+ # family_admin. Together they cross 10,000, the shared one alone does not.+ def shared_and_private_balances+ period = Period.last_30_days+ create_balance(account: accounts(:depository), date: period.start_date, balance: 9_000)+ create_balance(account: accounts(:depository), date: period.end_date, balance: 9_500)+ create_balance(account: accounts(:connected), date: period.start_date, balance: 0)+ create_balance(account: accounts(:connected), date: period.end_date, balance: 2_000)+ end+# Sets the family's net worth from N days ago onwards; each value holds# until the next one.def net_worth(values_by_days_ago)diff --git a/test/models/insight/generators/savings_rate_change_generator_test.rb b/test/models/insight/generators/savings_rate_change_generator_test.rbnew file mode 100644index 0000000000..704f0b2202--- /dev/null+++ b/test/models/insight/generators/savings_rate_change_generator_test.rb@@ -0,0 +1,33 @@+require "test_helper"++class Insight::Generators::SavingsRateChangeGeneratorTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @family = families(:dylan_family)+ end++ # Far enough back that the relative-date fixture entries fall after it.+ def today+ @today ||= (Date.current - 6.months).change(day: 15)+ end++ # Both months save half of a 1,000 income on the shared `depository`. The+ # extra spend sits on `connected`, private to family_admin, so the shared+ # feed must not read it as a drop in the family's savings rate.+ test "ignores spending on an account private to one member" do+ travel_to today do+ last_month = Period.last_month_for(@family).start_date+ prior_month = last_month - 1.month++ [ prior_month, last_month ].each do |month|+ create_transaction(amount: -1_000, date: month.change(day: 2), name: "salary #{month}")+ create_transaction(amount: 500, date: month.change(day: 5), name: "rent #{month}")+ end+ create_transaction(amount: 400, date: last_month.change(day: 9), name: "private",+ account: accounts(:connected))++ assert_empty Insight::Generators::SavingsRateChangeGenerator.new(@family).generate+ end+ end+enddiff --git a/test/models/insight/generators/spending_anomaly_generator_test.rb b/test/models/insight/generators/spending_anomaly_generator_test.rbindex d0480867ee..aa1c89152b 100644--- a/test/models/insight/generators/spending_anomaly_generator_test.rb+++ b/test/models/insight/generators/spending_anomaly_generator_test.rb@@ -55,4 +55,17 @@ class Insight::Generators::SpendingAnomalyGeneratorTest < ActiveSupport::TestCasassert_equal "high", insights.first.priorityendend++ # The same spike as above, but booked on `connected`, which is private to+ # family_admin. The shared feed must not report a category total built+ # from it.+ test "ignores spending on an account private to one member" do+ travel_to anchor do+ 3.times { |i| spend(month_start(i + 1), 1_000) }+ create_transaction(category: @category, amount: 1_000, date: anchor.beginning_of_month.change(day: 3),+ name: "private spike", account: accounts(:connected))++ assert_empty generate+ end+ endenddiff --git a/test/models/insight/generators/subscription_audit_generator_test.rb b/test/models/insight/generators/subscription_audit_generator_test.rbindex 1c9a477e23..b29392e787 100644--- a/test/models/insight/generators/subscription_audit_generator_test.rb+++ b/test/models/insight/generators/subscription_audit_generator_test.rb@@ -1,6 +1,8 @@require "test_helper"class Insight::Generators::SubscriptionAuditGeneratorTest < ActiveSupport::TestCase+ include EntriesTestHelper+setup do@family = families(:dylan_family)@overdue = recurring_transactions(:netflix_subscription)@@ -48,4 +50,63 @@ class Insight::Generators::SubscriptionAuditGeneratorTest < ActiveSupport::TestCassert_empty insightsend++ test "names the account the subscription is paid from" do+ insight = Insight::Generators::SubscriptionAuditGenerator.new(@family).generate.first++ assert_equal @overdue.account_id, insight.metadata[:account_id]+ end++ test "skips a subscription paid from an account private to one member" do+ @overdue.update_columns(account_id: accounts(:connected).id)++ insights = Insight::Generators::SubscriptionAuditGenerator.new(@family).generate++ assert_empty insights+ end++ test "keeps a subscription that has no account" do+ @overdue.update_columns(account_id: nil)++ insights = Insight::Generators::SubscriptionAuditGenerator.new(@family).generate++ assert_equal [ "subscription_audit:#{@overdue.id}" ], insights.map(&:dedup_key)+ assert_not insights.first.metadata.key?(:account_id)+ end++ test "skips an accountless series whose last-payment amount came from a private account" do+ pay_previous_occurrence_from(accounts(:connected))++ insights = Insight::Generators::SubscriptionAuditGenerator.new(@family).generate++ assert_empty insights+ end++ test "keeps an accountless series whose payments came from shared accounts" do+ pay_previous_occurrence_from(accounts(:depository))++ insights = Insight::Generators::SubscriptionAuditGenerator.new(@family).generate++ assert_equal [ "subscription_audit:#{@overdue.id}" ], insights.map(&:dedup_key)+ end++ test "keeps an accountless fixed-amount series even when a private account paid it" do+ pay_previous_occurrence_from(accounts(:connected))+ @overdue.update_columns(amount_strategy: "fixed")++ insights = Insight::Generators::SubscriptionAuditGenerator.new(@family).generate++ assert_equal [ "subscription_audit:#{@overdue.id}" ], insights.map(&:dedup_key)+ end++ private+ def pay_previous_occurrence_from(account)+ @overdue.update_columns(account_id: nil, amount_strategy: "last")+ entry = create_transaction(account: account, amount: 23.45, date: 80.days.ago.to_date)+ paid = @overdue.recurring_occurrences.create!(+ family: @family, original_due_on: 80.days.ago.to_date, due_on: 80.days.ago.to_date,+ currency: @overdue.currency, status: "paid", closed_at: 80.days.ago, closed_source: "user"+ )+ paid.allocations.create!(allocated_amount: 23.45, currency: @overdue.currency, source: "user_confirmed", entry: entry)+ endenddiff --git a/test/models/insight_test.rb b/test/models/insight_test.rbindex d91619b794..967bb8751c 100644--- a/test/models/insight_test.rb+++ b/test/models/insight_test.rb@@ -166,7 +166,38 @@ class InsightTest < ActiveSupport::TestCaseassert_not_includes family.insights.visible, insightend+ test "an insight about a recurring series follows the series' current account" do+ family = families(:dylan_family)+ series = recurring_transactions(:netflix_subscription)+ insight = subscription_audit_insight(family, series, account_id: series.account_id)+ assert_includes family.insights.visible, insight++ series.update_columns(account_id: accounts(:connected).id)+ assert_not_includes family.insights.visible, insight++ series.update_columns(account_id: nil)+ assert_includes family.insights.visible, insight+ end++ test "an insight about a deleted recurring series is hidden" do+ family = families(:dylan_family)+ series = recurring_transactions(:netflix_subscription)+ insight = subscription_audit_insight(family, series)++ series.destroy!++ assert_not_includes family.insights.visible, insight+ end+private+ def subscription_audit_insight(family, series, account_id: nil)+ family.insights.create!(+ insight_type: "subscription_audit", priority: "medium", status: "active", title: "Audit", body: "body",+ metadata: { "recurring_transaction_id" => series.id, "account_id" => account_id }.compact,+ dedup_key: "subscription_audit:#{series.id}", generated_at: Time.current+ )+ end+def idle_cash_insight(family, account)family.insights.create!(insight_type: "idle_cash", priority: "low", status: "active", title: "Idle", body: "body",