The personal finance app for everyone (by everyone)
Ruby
Count income and snoozed dates in the cash flow warning (#5845)
GFR3288613f52a4
diff --git a/app/models/insight/generators/cash_flow_warning_generator.rb b/app/models/insight/generators/cash_flow_warning_generator.rbindex 10031b6a65..1e156771c0 100644--- a/app/models/insight/generators/cash_flow_warning_generator.rb+++ b/app/models/insight/generators/cash_flow_warning_generator.rb@@ -17,25 +17,34 @@ class Insight::Generators::CashFlowWarningGenerator < Insight::Generatorreturn [] if accounts.empty?starting_balance = accounts.sum(:balance).to_d- entries = upcoming_recurring_entries- recurring_by_date = entries.group_by(&:date)+ flows = upcoming_recurring_flows(accounts)+ return [] if flows.empty? && median_monthly_expense <= 0++ # Money due out today may already be in the balance, so it is neither+ # subtracted nor taken out of the baseline; income due today and still+ # open has not arrived yet and counts from the start (as in+ # BillNotCoveredGenerator).+ today_flows, later_flows = flows.partition { |flow| flow.date == Date.current }+ flows_by_date = later_flows.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 }+ # Income is not part of the expense median, so it only adds on its date.+ # A bill snoozed out of the horizon will not be paid in it either, so it+ # leaves the baseline although it is not applied on any date. An overdue+ # bill snoozed into the horizon is applied on its new date but stays in the+ # baseline: the median does not hold it.+ recurring_expense_total = later_flows.select(&:in_median).sum { |flow| -flow.amount } + snoozed_out_expense_totalother_daily_spend = [ median_monthly_expense - recurring_expense_total, 0.to_d ].max / HORIZON_DAYS- balance = starting_balance- low_point = starting_balance+ balance = starting_balance + today_flows.sum { |flow| [ flow.amount, 0.to_d ].max }+ low_point = balancelow_date = Date.current(1..HORIZON_DAYS).each do |offset|date = Date.current + offsetbalance -= other_daily_spend- recurring_by_date.fetch(date, []).each { |e| balance -= e.amount.to_d }+ flows_by_date.fetch(date, []).each { |flow| balance += flow.amount }if balance < low_pointlow_point = balance@@ -79,9 +88,17 @@ class Insight::Generators::CashFlowWarningGenerator < Insight::Generatorshared_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 median_monthly_expense+ @median_monthly_expense ||= income_statement.median_expense(interval: "month").to_d+ end++ # Signed flows of known recurring transactions within the horizon:+ # negative for bills, positive for income. Transfers are internal moves+ # (and loan or investment contributions are already in the expense+ # median), and cross-currency amounts can't be applied to a+ # family-currency balance without a rate lookup, so both are skipped.+ # Income only counts when it lands in one of the projected cash accounts;+ # a salary paid into a private account does not cover the shared balance.## Deliberately NOT gated on family.recurring_transactions_disabled?, unlike# SubscriptionAuditGenerator. That generator's entire subject is "your@@ -93,29 +110,76 @@ class Insight::Generators::CashFlowWarningGenerator < Insight::Generator# (IdentifyRecurringTransactionsJob) — it doesn't clear out ones already# identified, so this keeps using that last-known set rather than silently# degrading to the flatter median-only baseline.- Obligation = Data.define(:date, :amount)+ # in_median: the occurrence was originally due inside the horizon, so the+ # monthly expense median already holds it. An overdue bill snoozed into+ # the horizon belongs to an earlier month and is spent on top of it.+ Flow = Data.define(:date, :amount, :in_median)# Occurrence rows instead of one projected entry per series: a weekly# bill contributes every hit inside the horizon (the single-projection# version silently under-counted it fourfold), and partially paid- # occurrences contribute only what actually remains.- def upcoming_recurring_entries- occurrences = family.recurring_occurrences+ # occurrences contribute only what actually remains. A snoozed occurrence+ # counts on the date it was snoozed to, including an overdue one snoozed+ # into the horizon; an overdue one that was not snoozed is left out, as the+ # balance cannot tell whether it was paid.+ def upcoming_recurring_flows(accounts)+ cash_account_ids = accounts.pluck(:id).to_set++ occurrences = load_occurrences(+ projected_occurrences.where("#{RecurringOccurrence::EFFECTIVE_DUE_ON_SQL} BETWEEN ? AND ?", Date.current, horizon_end)+ )++ occurrences.filter_map do |occurrence|+ series = occurrence.recurring_transaction+ remaining = occurrence.remaining_amount.to_d+ next unless remaining.positive?++ if series.amount.negative?+ next unless cash_account_ids.include?(series.account_id)++ Flow.new(date: occurrence.effective_due_on, amount: remaining, in_median: false)+ else+ Flow.new(date: occurrence.effective_due_on, amount: -remaining, in_median: occurrence.due_on >= Date.current)+ end+ end+ end++ # Bills originally due inside the horizon but snoozed past it: what+ # remains of them is part of the monthly expense median, yet nothing of it+ # will be spent in this window.+ def snoozed_out_expense_total+ occurrences = load_occurrences(+ projected_occurrences+ .where(due_on: Date.current..horizon_end)+ .where("#{RecurringOccurrence::EFFECTIVE_DUE_ON_SQL} > ?", horizon_end)+ )++ occurrences.sum do |occurrence|+ next 0.to_d if occurrence.recurring_transaction.amount.negative?++ [ occurrence.remaining_amount.to_d, 0.to_d ].max+ end+ end++ def projected_occurrences+ family.recurring_occurrences.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))- .includes(:recurring_transaction)- .to_a+ end- # remaining_amount reads the confirmed-allocation sum, and this runs- # nightly for every family: one grouped query instead of one SUM per- # occurrence in the horizon.- RecurringOccurrence.preload_confirmed_allocated(occurrences)+ # remaining_amount reads the confirmed-allocation sum, and this runs+ # nightly for every family: one grouped query instead of one SUM per+ # occurrence.+ def load_occurrences(scope)+ scope.includes(:recurring_transaction).to_a.tap do |occurrences|+ RecurringOccurrence.preload_confirmed_allocated(occurrences)+ end+ end- occurrences.map { |occurrence| Obligation.new(date: occurrence.due_on, amount: occurrence.remaining_amount) }+ def horizon_end+ Date.current + HORIZON_DAYSendenddiff --git a/test/models/insight/generators/cash_flow_warning_generator_test.rb b/test/models/insight/generators/cash_flow_warning_generator_test.rbindex bf23ca5116..bf15253fb1 100644--- a/test/models/insight/generators/cash_flow_warning_generator_test.rb+++ b/test/models/insight/generators/cash_flow_warning_generator_test.rb@@ -34,11 +34,11 @@ class Insight::Generators::CashFlowWarningGeneratorTest < ActiveSupport::TestCasendentries = ActiveSupport::Notifications.subscribed(counter, "sql.active_record") do- generator.send(:upcoming_recurring_entries)+ generator.send(:upcoming_recurring_flows, generator.send(:cash_accounts))endassert_equal 1, sum_queries, "the confirmed-allocation sums must batch into one grouped query"- assert_equal [ 60, 100, 100 ], entries.sort_by(&:date).map(&:amount).map(&:to_i),+ assert_equal [ -60, -100, -100 ], entries.sort_by(&:date).map(&:amount).map(&:to_i),"the partially paid occurrence contributes only its remainder"end@@ -65,9 +65,7 @@ class Insight::Generators::CashFlowWarningGeneratorTest < ActiveSupport::TestCasfamily: @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+ assert_equal [ -100, -100, -60 ], flow_amountsendtest "an inactive member does not hide an account from the projection" do@@ -77,4 +75,151 @@ class Insight::Generators::CashFlowWarningGeneratorTest < ActiveSupport::TestCasassert_empty Insight::Generators::CashFlowWarningGenerator.new(@family).generateend++ test "scheduled income into a projected cash account lifts the projection" do+ clear_schedule+ IncomeStatement.any_instance.stubs(:median_expense).returns(2_500)+ accounts(:depository).update_columns(balance: 1_500)+ schedule("Salary", -3_000, Date.current + 5)++ # Without the salary the 30-day baseline alone takes 1,500 to -1,000; with+ # it the low point is about 1,167, the day before it arrives.+ assert_empty generate+ end++ test "income into a private account does not cover the shared balance" do+ clear_schedule+ IncomeStatement.any_instance.stubs(:median_expense).returns(2_500)+ accounts(:depository).update_columns(balance: 1_500)+ schedule("Private salary", -3_000, Date.current + 5, account: accounts(:connected))++ assert_equal [], flow_amounts+ assert_equal "cash_flow_warning.negative", generate.first.template_key+ end++ # The credit card is visible to every member, so the series passes the+ # shared-series scope; only the cash-account check keeps it out.+ test "income into a shared account that is not projected cash does not count" do+ clear_schedule+ IncomeStatement.any_instance.stubs(:median_expense).returns(2_500)+ accounts(:depository).update_columns(balance: 1_500)+ schedule("Card refund", -3_000, Date.current + 5, account: accounts(:credit_card))++ assert_equal [], flow_amounts+ assert_equal "cash_flow_warning.negative", generate.first.template_key+ end++ # Out of the shared cash account, so only the transfer guard keeps it out.+ test "a scheduled transfer is not counted as a bill" do+ clear_schedule+ schedule("To card", 3_000, Date.current + 5, destination: accounts(:credit_card))++ assert_equal [], flow_amounts+ end++ test "a bill snoozed past the horizon is not projected on its original date" do+ clear_schedule+ IncomeStatement.any_instance.stubs(:median_expense).returns(0)+ accounts(:depository).update_columns(balance: 1_000)+ schedule("Insurance", 800, Date.current + 3).snooze!(Date.current + 45)++ assert_empty generate+ end++ test "a bill snoozed past the horizon leaves the spending baseline" do+ clear_schedule+ IncomeStatement.any_instance.stubs(:median_expense).returns(800)+ accounts(:depository).update_columns(balance: 1_000)+ schedule("Insurance", 800, Date.current + 3).snooze!(Date.current + 45)++ assert_empty generate+ end++ test "an overdue bill snoozed into the horizon counts on its new date" do+ clear_schedule+ IncomeStatement.any_instance.stubs(:median_expense).returns(0)+ accounts(:depository).update_columns(balance: 1_000)+ schedule("Tax", 800, Date.current - 2).snooze!(Date.current + 4)++ insights = generate++ assert_equal 1, insights.size+ assert_equal I18n.l(Date.current + 4), insights.first.facts[:projected_low_date]+ assert_equal Money.new(200, "USD").format, insights.first.facts[:projected_low]+ end++ # The overdue occurrence belongs to last month; only next month's (day 25)+ # is part of the median, so only that one leaves the spending baseline.+ test "an overdue bill snoozed into the horizon is spent on top of the median" do+ clear_schedule+ IncomeStatement.any_instance.stubs(:median_expense).returns(1_200)+ accounts(:depository).update_columns(balance: 1_500)+ series = schedule("Rent", 600, Date.current + 25).recurring_transaction+ series.recurring_occurrences.create!(+ family: @family, original_due_on: Date.current - 5, due_on: Date.current - 5, currency: "USD"+ ).snooze!(Date.current + 4)++ insight = generate.first++ # 1,500 - 600 (overdue) - 600 (next) - 600 (rest of the median) = -300.+ assert_equal "cash_flow_warning.negative", insight.template_key+ assert_equal Money.new(-300, "USD").format, insight.facts[:projected_low]+ end++ test "an overdue bill that was not snoozed is left out" do+ clear_schedule+ schedule("Tax", 800, Date.current - 2)++ assert_equal [], flow_amounts+ end++ # The bill may already be in today's balance, so it is not subtracted again,+ # but it stays in the spending baseline instead of vanishing from both.+ test "an open bill due today stays in the baseline" do+ clear_schedule+ IncomeStatement.any_instance.stubs(:median_expense).returns(600)+ accounts(:depository).update_columns(balance: 1_000)+ schedule("Rent", 600, Date.current)++ insights = generate++ assert_equal 1, insights.size+ assert_equal Money.new(400, "USD").format, insights.first.facts[:projected_low]+ end++ test "open income due today counts from the start" do+ clear_schedule+ IncomeStatement.any_instance.stubs(:median_expense).returns(300)+ accounts(:depository).update_columns(balance: 100)+ schedule("Salary", -1_000, Date.current)++ assert_empty generate+ end++ private+ def generate+ Insight::Generators::CashFlowWarningGenerator.new(@family).generate+ end++ def flow_amounts+ generator = Insight::Generators::CashFlowWarningGenerator.new(@family)+ generator.send(:upcoming_recurring_flows, generator.send(:cash_accounts)).map { |flow| flow.amount.to_i }.sort+ end++ # Only the shared checking account holds cash, and only the series a test+ # schedules are open.+ def clear_schedule+ @family.recurring_transactions.destroy_all+ @family.accounts.where.not(id: accounts(:depository).id).where(accountable_type: "Depository").update_all(balance: 0)+ end++ def schedule(name, amount, due_on, account: accounts(:depository), destination: nil)+ series = @family.recurring_transactions.create!(+ name: name, account: account, destination_account: destination, amount: amount, 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+ )+ series.recurring_occurrences.delete_all+ series.recurring_occurrences.create!(family: @family, original_due_on: due_on, due_on: due_on, currency: "USD")+ endend