The personal finance app for everyone (by everyone)
Ruby
fix(insights): stop flagging planned bills and payday timing as spending changes (#5114)
David Gil74129de1aff3
diff --git a/app/helpers/insights_helper.rb b/app/helpers/insights_helper.rbindex 3cd10e7e43..0a4ca16c0c 100644--- a/app/helpers/insights_helper.rb+++ b/app/helpers/insights_helper.rb@@ -62,7 +62,7 @@ module InsightsHelperwhen "savings_rate_change"return nil unless facts["change_pp"]sign = insight_sentiment(insight) == :positive ? "+" : "−"- [ "#{sign}#{facts["change_pp"]} pp", t("insights.figures.vs_previous") ]+ [ "#{sign}#{facts["change_pp"]} pp", t("insights.figures.vs_previous_three_months") ]when "net_worth_milestone"facts["net_worth"] && [ facts["net_worth"], t("insights.figures.today") ]when "spending_anomaly"@@ -214,8 +214,9 @@ module InsightsHelperelsif rolling_period_insight?(insight) && end_date >= Date.current - 1t("insights.meta.last_n_days", count: days)elsif start_date == start_date.beginning_of_month && end_date == start_date.end_of_month- format = start_date.year == Date.current.year ? "%B" : "%B %Y"- I18n.l(start_date, format: format)+ insight_month_name(start_date)+ elsif start_date == start_date.beginning_of_month && end_date == end_date.end_of_month+ t("insights.meta.date_range", from: insight_month_name(start_date), to: insight_month_name(end_date))elsif start_date >= Date.current - 1t("insights.meta.next_n_days", count: days)elsif end_date >= Date.current - 1@@ -225,6 +226,10 @@ module InsightsHelperendend+ def insight_month_name(date)+ I18n.l(date, format: date.year == Date.current.year ? "%B" : "%B %Y")+ end+def rolling_period_insight?(insight)insight.insight_type.in?(%w[cash_flow_warning net_worth_milestone])enddiff --git a/app/models/budget.rb b/app/models/budget.rbindex 45324804d8..83b730b873 100644--- a/app/models/budget.rb+++ b/app/models/budget.rb@@ -416,37 +416,22 @@ class Budget < ApplicationRecordenddef budget_category_actual_spending(budget_category)- key = budget_category.category_id || stable_synthetic_key(budget_category.category)- expense = expense_totals_by_category[key]&.total || 0- refund = income_totals_by_category[key]&.total || 0- [ expense - refund, 0 ].max+ actual_spending_for(category_key(budget_category))+ end++ # The part of budget_category_actual_spending that paid bills. Gross of+ # refunds, which actual spending nets: a refund lowers the spending outside+ # bills, which errs towards fewer warnings.+ def budget_category_bills_paid(budget_category)+ bills_paid_for(category_key(budget_category))end# Open bill occurrences due in this period, by category id, loaded once so# each BudgetCategory#bills_reserved reads its slice instead of querying.def open_bill_occurrences_by_category_id- @open_bill_occurrences_by_category_id ||= begin- occurrences = RecurringOccurrence- .open_status- .joins(:recurring_transaction)- .where(recurring_transactions: {- family_id: family_id,- status: :active,- destination_account_id: nil- })- .where("recurring_transactions.amount > 0")- .where(due_on: start_date..end_date)- .includes(:recurring_transaction)- .to_a-- sums = RecurringAllocation.confirmed- .where(recurring_occurrence_id: occurrences.map(&:id))- .group(:recurring_occurrence_id)- .sum(:allocated_amount)- occurrences.each { |occurrence| occurrence.cached_confirmed_allocated = sums.fetch(occurrence.id, 0) }-- occurrences.group_by { |occurrence| occurrence.recurring_transaction.category_id }- end+ @open_bill_occurrences_by_category_id ||= RecurringOccurrence+ .open_bills_due(family, start_date..end_date)+ .group_by { |occurrence| occurrence.recurring_transaction.category_id }enddef category_median_monthly_expense(category)@@ -467,6 +452,21 @@ class Budget < ApplicationRecord(actual_spending / budgeted_spending.to_f) * 100end+ # The part of actual_spending that paid bills, line by line: a line's+ # refunds can bring its spending below its bills, and actual_spending only+ # counts what is left. Uncategorized spending is in actual_spending, so its+ # synthetic line is counted too.+ def bills_paid+ keys = budget_categories.reject(&:subcategory?).map { |bc| category_key(bc) } + [ :uncategorized ]+ keys.uniq.sum { |key| [ bills_paid_for(key), actual_spending_for(key) ].min }+ end++ # The rule each line follows (BudgetCategory#near_limit?), for the whole budget.+ def near_limit?+ !available_to_spend.negative? && percent_of_budget_spent >= BudgetCategory::NEAR_LIMIT_PERCENT &&+ BudgetCategory.near_limit_outside_bills?(spent: actual_spending, bills_paid: bills_paid, available: available_to_spend)+ end+def overage_percentreturn 0 unless available_to_spend.negative?@@ -584,6 +584,22 @@ class Budget < ApplicationRecord@income_totals_by_category ||= income_totals.category_totals.index_by { |ct| ct.category.id || stable_synthetic_key(ct.category) }end+ def category_key(budget_category)+ budget_category.category_id || stable_synthetic_key(budget_category.category)+ end++ def actual_spending_for(key)+ expense = expense_totals_by_category[key]&.total || 0+ refund = income_totals_by_category[key]&.total || 0+ [ expense - refund, 0 ].max+ end++ def bills_paid_for(key)+ @bill_expense_totals_by_category ||= income_statement.bill_expense_totals(period: period)+ .category_totals.index_by { |ct| ct.category.id || stable_synthetic_key(ct.category) }+ @bill_expense_totals_by_category[key]&.total || 0+ end+def stable_synthetic_key(category)if category.uncategorized?:uncategorizeddiff --git a/app/models/budget_category.rb b/app/models/budget_category.rbindex 0cb4c3c929..fa43e4f0d0 100644--- a/app/models/budget_category.rb+++ b/app/models/budget_category.rb@@ -23,6 +23,8 @@ class BudgetCategory < ApplicationRecordvalidates :budget_id, uniqueness: { scope: :category_id }+ NEAR_LIMIT_PERCENT = 90+monetize :budgeted_spending, :available_to_spend, :avg_monthly_expense, :median_monthly_expense, :actual_spending,:rolled_over_amount@@ -47,6 +49,13 @@ class BudgetCategory < ApplicationRecordendclass << self+ # The near-limit test on spending outside bills, shared with+ # Budget#near_limit? so a budget and its lines warn alike.+ def near_limit_outside_bills?(spent:, bills_paid:, available:)+ unplanned = spent - bills_paid+ unplanned.positive? && unplanned / (available + unplanned) * 100 >= NEAR_LIMIT_PERCENT+ end+def uncategorizednew(id: Digest::UUID.uuid_v5(Digest::UUID::URL_NAMESPACE, "uncategorized"),@@ -162,6 +171,13 @@ class BudgetCategory < ApplicationRecordbudget.budget_category_actual_spending(self)end+ # The part of actual_spending that paid bills inside the budget period.+ # Unlike bills_reserved it counts a parent's subcategories, as+ # actual_spending does.+ def bills_paid+ budget.budget_category_bills_paid(self)+ end+# The toggle is a standing choice about the envelope, and the comment on# Budget#inherited_rollover_flags already says so: "turning it off on a given# month still overrides it from there on."@@ -367,8 +383,18 @@ class BudgetCategory < ApplicationRecordactual_spending.to_d.positive?end+ # Close to the limit for spending outside bills. Fixed charges that land+ # early fill the envelope without using anything up: a line whose gym fee+ # and medical plan are its whole budget sits at 100% on day 5 with nothing+ # left to watch. So the spending outside bills is measured against what the+ # bills paid so far leave of the envelope. Without bills that is the plain+ # share of the envelope spent. The percent check comes first only to skip+ # the bills query for lines nowhere near the limit. For a subcategory+ # sharing its parent's budget, available_to_spend is the shared pool, so the+ # measure is approximate there.def near_limit?- !over_budget? && percent_of_budget_spent >= 90+ !over_budget? && percent_of_budget_spent >= NEAR_LIMIT_PERCENT &&+ self.class.near_limit_outside_bills?(spent: actual_spending, bills_paid: bills_paid, available: available_to_spend)end# Returns hash with suggested daily spending info or nil if not applicable@@ -425,7 +451,7 @@ class BudgetCategory < ApplicationRecordtotal = occurrences.reduce(Money.new(0, currency)) do |sum, occurrence|begin- sum + occurrence.remaining_amount_money.exchange_to(currency)+ sum + occurrence.remaining_spending_money.exchange_to(currency)rescue Money::ConversionErrorunconvertible += 1sumdiff --git a/app/models/entry.rb b/app/models/entry.rbindex ae8d783046..0ba1a278f0 100644--- a/app/models/entry.rb+++ b/app/models/entry.rb@@ -153,6 +153,10 @@ class Entry < ApplicationRecordSQL}+ # The entries in `ids` and the children of any of them that was split, which+ # stand in for their excluded parent wherever money is counted.+ scope :with_split_children, ->(ids) { where(id: ids).or(where(parent_entry_id: ids)) }+# Future-dated entries haven't happened yet, so "actual" reporting (budgets,# income statement, insights) should not count them until their date# arrives -- see Entry#scheduled?.diff --git a/app/models/income_statement.rb b/app/models/income_statement.rbindex 66a4dcb9c9..1376c4073e 100644--- a/app/models/income_statement.rb+++ b/app/models/income_statement.rb@@ -44,6 +44,28 @@ class IncomeStatement@expense_totals_by_period[key] = build_period_total(classification: "expense", period: period)end+ # The part of expense_totals that paid the family's bills: the same+ # filters, currency conversion and roll-up into parent categories, so the+ # two subtract cleanly. A payment counts once at its entry's amount, however+ # many occurrences it settles. A payment that was split counts through its+ # children, so only the parts that are spending, each in its own category.+ def bill_expense_totals(period: Period.current_month)+ key = period_cache_key(period)+ @bill_expense_totals_by_period ||= {}+ return @bill_expense_totals_by_period[key] if @bill_expense_totals_by_period.key?(key)++ paying_bills = Entry.where(entryable_type: "Transaction")+ .with_split_children(RecurringAllocation.to_family_bills(family).select(:entry_id))+ .select(:entryable_id)+ rows = totals_query(+ transactions_scope: family.transactions.visible.excluding_pending.merge(Entry.excluding_scheduled)+ .in_period(period).where(id: paying_bills),+ date_range: period.date_range,+ freshness: bill_allocations_version+ )+ @bill_expense_totals_by_period[key] = build_period_total(classification: "expense", period: period, rows: rows)+ end+def income_totals(period: Period.current_month)key = period_cache_key(period)@income_totals_by_period ||= {}@@ -209,9 +231,9 @@ class IncomeStatement[ period.start_date, period.end_date ]end- def build_period_total(classification:, period:)+ def build_period_total(classification:, period:, rows: totals_for_period(period))# Exclude pending transactions from budget calculations- totals = totals_for_period(period).select { |t| t.classification == classification }+ totals = rows.select { |t| t.classification == classification }classification_total = totals.sum(&:total)uncategorized_category = family.categories.uncategorized@@ -344,6 +366,19 @@ class IncomeStatement# Rates, target currency, tag membership and whether investing counts as# spending can change without touching entries or accounts. Scheduled entries are# excluded as of "today", so the key also rolls over daily.+ # Linking or unlinking a payment doesn't touch its entry, so the bill+ # totals' cache key also tracks the allocations and series they read.+ def bill_allocations_version+ @bill_allocations_version ||= begin+ count, allocated_at, series_at = RecurringAllocation.to_family_bills(family).pick(+ Arel.sql("COUNT(*)"),+ Arel.sql("MAX(recurring_allocations.updated_at)"),+ Arel.sql("MAX(recurring_transactions.updated_at)")+ )+ [ count, allocated_at&.to_f, series_at&.to_f ]+ end+ end+def cache_freshness_key@cache_freshness_key ||= [Date.current,@@ -356,11 +391,13 @@ class IncomeStatement]end- def totals_query(transactions_scope:, date_range:)+ # `freshness` adds whatever else the scope reads beyond the entries the+ # default key already tracks.+ def totals_query(transactions_scope:, date_range:, freshness: nil)sql_hash = Digest::MD5.hexdigest(transactions_scope.to_sql)Rails.cache.fetch([- "income_statement", "totals_query", "v2", ExchangeRate::CONVERSION_CACHE_VERSION, family.id, user&.id, included_account_ids_hash, sql_hash, date_range.begin, date_range.end, *cache_freshness_key+ "income_statement", "totals_query", "v2", ExchangeRate::CONVERSION_CACHE_VERSION, family.id, user&.id, included_account_ids_hash, sql_hash, date_range.begin, date_range.end, *cache_freshness_key, *freshness]) { Totals.new(family, transactions_scope: transactions_scope, date_range: date_range, included_account_ids: included_account_ids).call }enddiff --git a/app/models/insight/generator.rb b/app/models/insight/generator.rbindex f115f67318..cd291a2a3b 100644--- a/app/models/insight/generator.rb+++ b/app/models/insight/generator.rb@@ -82,6 +82,22 @@ class Insight::Generator.or(RecurringTransaction.where(account_id: shared_accounts.select(:id)))end+ # The household budget: the feed is shared by the whole family, so one+ # member's personal budget can't speak for it. 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+ return @current_budget if defined?(@current_budget)++ @current_budget = family.budgets+ .where(user_id: nil)+ .includes(budget_categories: :category)+ .where("start_date <= ? AND end_date >= ?", Date.current, Date.current)+ .first+ @current_budget&.income_statement_accounts = shared_accounts+ @current_budget+ end+def build_insight(insight_type:, priority:, title:, template_key:, facts:, dedup_key:, metadata:, period: nil)GeneratedInsight.new(insight_type: insight_type,diff --git a/app/models/insight/generators/budget_insight_generator.rb b/app/models/insight/generators/budget_insight_generator.rbindex ba9be35767..3712c1254d 100644--- a/app/models/insight/generators/budget_insight_generator.rb+++ b/app/models/insight/generators/budget_insight_generator.rb@@ -37,20 +37,6 @@ class Insight::Generators::BudgetInsightGenerator < Insight::Generatorincome_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- 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- budget- end-def at_risk_insight(budget, over, near)flagged = over + nearcategory_names = flagged.first(MAX_LISTED_CATEGORIES).map { |bc| bc.category.name }diff --git a/app/models/insight/generators/savings_rate_change_generator.rb b/app/models/insight/generators/savings_rate_change_generator.rbindex d02fbd8b8b..84e0d74d3f 100644--- a/app/models/insight/generators/savings_rate_change_generator.rb+++ b/app/models/insight/generators/savings_rate_change_generator.rb@@ -1,30 +1,35 @@-# 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.+# Compares the savings rate of the last three complete months with that of+# the three before. A monthly rate mostly measures which day the salary+# landed: paid on the 29th instead of the 1st, one month gets two salaries and+# the next none. So each window's income is its median month times three, which+# ignores a paycheck that moved to a neighbouring month wherever it falls,+# while spending is summed so a real one-off cost still shows. The current+# (partial) month is skipped for the same reason.class Insight::Generators::SavingsRateChangeGenerator < Insight::Generatorproduces "savings_rate_change"+ WINDOW_MONTHS = 3THRESHOLD_PP = 5HIGH_PRIORITY_PP = 10def generatelast_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)+ window_start = last_month.start_date - (WINDOW_MONTHS - 1).months+ window = Period.custom(start_date: window_start, end_date: last_month.end_date)- current_rate = savings_rate(last_month)- previous_rate = savings_rate(prior_month)+ current_rate = savings_rate(window_start)+ previous_rate = savings_rate(window_start - WINDOW_MONTHS.months)return [] unless current_rate && previous_ratedelta = current_rate - previous_ratereturn [] if delta.abs < THRESHOLD_PPdirection = 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?+ # "You saved -5.4% of your income" is machine-speak: when the family spent+ # more than it earned, the copy says so. Decided on the window's actual+ # totals, since the median-based rate can be negative after a bonus month.+ template_key = if direction == "down" && current_rate.negative? && spent_more_than_earned?(window_start)"savings_rate_change.down_negative"else"savings_rate_change.#{direction}"@@ -34,31 +39,65 @@ class Insight::Generators::SavingsRateChangeGenerator < Insight::Generatorbuild_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),+ title: I18n.t("insights.titles.savings_rate_change.#{direction}"),template_key: template_key,facts: {- month: month_name,+ from_month: window_bound(window.start_date, window.start_date),+ to_month: window_bound(last_month.start_date, window.end_date),current_rate: signed_number(round(current_rate, 1)),previous_rate: signed_number(round(previous_rate, 1)),change_pp: round(delta.abs, 1)},+ # Both windows hold only complete months, so these stay put for the+ # whole month and the nightly run doesn't reopen a dismissal. "v2"+ # because month-against-month rows still carry this month's key.metadata: {current_rate: round(current_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)}"+ period: window,+ dedup_key: "savings_rate_change:v2:#{month_token(last_month.start_date)}")]endprivate- def savings_rate(period)- income = income_statement.income_totals(period: period).total.to_d+ # The rate of the window of WINDOW_MONTHS months starting on `start_date`.+ def savings_rate(start_date)+ incomes, expense = window_totals(start_date)+ income = incomes.sort[WINDOW_MONTHS / 2] * WINDOW_MONTHS # the median: WINDOW_MONTHS is oddreturn nil if income <= 0- expense = income_statement.expense_totals(period: period).total.to_d(income - expense) / income * 100end++ def spent_more_than_earned?(start_date)+ incomes, expense = window_totals(start_date)+ expense > incomes.sum+ end++ # [each month's income, the window's summed spending].+ def window_totals(start_date)+ months = Array.new(WINDOW_MONTHS) do |i|+ month_start = start_date + i.months+ Period.custom(start_date: month_start, end_date: month_start + 1.month - 1.day)+ end++ [+ months.map { |month| income_statement.income_totals(period: month).total.to_d },+ months.sum { |month| income_statement.expense_totals(period: month).total.to_d }+ ]+ end++ # Month names for calendar months; for months that start on another day+ # (a custom month start) the window's dates, which month names would+ # misreport.+ def window_bound(month_start, date)+ if month_start == month_start.beginning_of_month+ I18n.l(month_start, format: "%B")+ else+ I18n.l(date, format: :short)+ end+ endenddiff --git a/app/models/insight/generators/spending_anomaly_generator.rb b/app/models/insight/generators/spending_anomaly_generator.rbindex 3286c1ea3b..2f7d01306f 100644--- a/app/models/insight/generators/spending_anomaly_generator.rb+++ b/app/models/insight/generators/spending_anomaly_generator.rb@@ -1,5 +1,11 @@# Flags parent categories whose current-month spending pace deviates from# their average over the previous three full months.+#+# Bills are planned spending. What they already took this month counts once at+# face value and what they still expect this month is added as it stands; only+# the rest is projected at the month's pace. A category is flagged only when+# its spending outside bills moves too, so a bill that changes the month (an+# annual premium, a payment that fell in the previous month) is not a trend.class Insight::Generators::SpendingAnomalyGenerator < Insight::Generatorproduces "spending_anomaly"@@ -15,7 +21,8 @@ class Insight::Generators::SpendingAnomalyGenerator < Insight::Generatorelapsed_days = (Date.current - period.start_date).to_i + 1return [] if elapsed_days < MIN_ELAPSED_DAYS- current = category_spend(period)+ @current_spend = spend_by_category(period)+ current = parents_only(@current_spend)return [] if current.empty?baseline = baseline_spend(period)@@ -23,19 +30,21 @@ class Insight::Generators::SpendingAnomalyGenerator < Insight::Generator# #days is the elapsed count and dividing by it would make the projection a# no-op. Take the month's true length from its start date, which is also# correct for families on a custom month start.- month_days = ((period.start_date + 1.month) - period.start_date).to_i- pace_factor = month_days.to_f / elapsed_days+ month_end = period.start_date + 1.month - 1.day+ pace_factor = (month_end - period.start_date + 1).to_f / elapsed_days+ bills_due = bills_still_due(period.start_date..month_end)anomalies = current.filter_map do |category_id, data|- baseline_amount = baseline[category_id]- next unless baseline_amount && baseline_amount >= MIN_BASELINE+ usual = baseline[category_id]+ next unless usual && usual[:total] >= MIN_BASELINE- projected = data[:total] * pace_factor- deviation_pct = (projected - baseline_amount) / baseline_amount * 100- next if deviation_pct.abs < DEVIATION_THRESHOLD_PCT+ due = bills_due.fetch(category_id, 0)+ projected, deviation_pct, unplanned_deviation_pct = project(data, data[:bills], due, usual, pace_factor)+ next unless significant?(deviation_pct, unplanned_deviation_pct)+ next if deviation_pct.positive? && paid_from_rollover?(category_id, data, due, usual, pace_factor){ category_id: category_id, name: data[:name], projected: projected,- baseline: baseline_amount, deviation_pct: deviation_pct }+ baseline: usual[:total], deviation_pct: deviation_pct }endanomalies@@ -74,30 +83,118 @@ class Insight::Generators::SpendingAnomalyGenerator < Insight::Generator)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)+ # Both the whole projection and its unplanned part have to clear the+ # threshold in the same direction.+ def significant?(deviation_pct, unplanned_deviation_pct)+ [ deviation_pct, unplanned_deviation_pct ].all? { |pct| pct.abs >= DEVIATION_THRESHOLD_PCT } &&+ deviation_pct.positive? == unplanned_deviation_pct.positive?+ end++ # [projected, deviation_pct, unplanned_deviation_pct]. `planned` counts+ # once at face value and `due` is added as it stands; only the rest of the+ # month-to-date spend is projected at the month's pace.+ def project(data, planned, due, usual, pace_factor)+ unplanned = (data[:total] - planned) * pace_factor+ projected = planned + due + unplanned+ [+ projected,+ (projected - usual[:total]) / usual[:total] * 100,+ (unplanned - (usual[:total] - usual[:bills])) / usual[:total] * 100+ ]+ end++ # Money saved up in a rollover envelope is there to be spent in a lump.+ # Counted as planned, like a bill, does the rise still stand? The envelope+ # may be the parent's or a ring-fenced subcategory's (Insurance under+ # Home), as long as it isn't overspent. Only the household budget counts.+ def paid_from_rollover?(category_id, data, due, usual, pace_factor)+ return false unless current_budget&.initialized?++ envelopes = current_budget.budget_categories.select do |bc|+ (bc.category_id == category_id || bc.category.parent_id == category_id) &&+ bc.rollover_enabled? && !bc.inherits_parent_budget? && !bc.over_budget?+ end+ saved = envelopes.sum { |bc| drawn_from_savings(bc, pace_factor) }+ return false unless saved.positive?++ planned = [ data[:bills] + saved, data[:total] ].min+ deviation_pct, unplanned_deviation_pct = project(data, planned, due, usual, pace_factor).drop(1)+ !(deviation_pct.positive? && significant?(deviation_pct, unplanned_deviation_pct))+ end++ # What an envelope has spent outside bills beyond its own allocation to+ # date, up to what it carried over: the part that came out of savings.+ # Spending within the month's allocation is ordinary spending, whatever+ # cushion sits behind it. Bills are already planned in `data[:bills]`, and+ # a parent leaves its ring-fenced subcategories to their own envelopes.+ # Spending is read gross of refunds, as the category's own is.+ def drawn_from_savings(envelope, pace_factor)+ spent, allocated = outside_bills(envelope)+ envelope.subcategories.reject(&:inherits_parent_budget?).each do |fenced|+ fenced_spent, fenced_allocated = outside_bills(fenced)+ spent -= fenced_spent+ allocated -= fenced_allocated+ end++ (spent - allocated.clamp(0, nil) / pace_factor).clamp(0, envelope.rolled_over_amount.to_d)+ end++ # [spent, allocated] for a budget line this month, less the bills it paid.+ def outside_bills(budget_category)+ spend = @current_spend.fetch(budget_category.category_id, { total: 0, bills: 0 })+ [ spend[:total], budget_category.budgeted_spending.to_d ].map { |amount| amount - spend[:bills] }+ end++ # { category_id => { name:, parent_id:, total:, bills: } } for persisted+ # categories, gross of refunds. Synthetic categories (uncategorized / other+ # investments) are too noisy to flag. `bills` is the part of `total` that+ # paid bills.+ def spend_by_category(period)+ bills = income_statement.bill_expense_totals(period: period).category_totals.to_h { |ct| [ ct.category.id, ct.total.to_d ] }+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 if ct.category.synthetic?next unless ct.total.positive?- totals[ct.category.id] = { name: ct.category.name, total: ct.total.to_d }+ totals[ct.category.id] = { name: ct.category.name, parent_id: ct.category.parent_id,+ total: ct.total.to_d, bills: bills.fetch(ct.category.id, 0) }endend+ # Only parent categories are flagged: subcategory spend is already rolled+ # into its parent's total.+ def parents_only(spend)+ spend.reject { |_, data| data[:parent_id] }+ end+def baseline_spend(current_period)- sums = Hash.new { |h, k| h[k] = 0.to_d }+ sums = Hash.new { |h, k| h[k] = { total: 0.to_d, bills: 0.to_d } }BASELINE_MONTHS.times do |i|start_date = current_period.start_date - (i + 1).monthsmonth = 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]+ parents_only(spend_by_category(month)).each do |category_id, data|+ sums[category_id][:total] += data[:total]+ sums[category_id][:bills] += data[:bills]endend- sums.transform_values { |total| total / BASELINE_MONTHS }+ sums.transform_values { |usual| usual.transform_values { |amount| amount / BASELINE_MONTHS } }+ end++ # What bills still expect this month, by parent category, in the family's+ # currency. Filed under the bill's own category, since there is no entry+ # yet to take one from. One with no rate is left out, as unplanned spending+ # would be. Only bills on shared accounts, like the spending they join.+ def bills_still_due(dates)+ parent_ids = family.categories.pluck(:id, :parent_id).to_h++ RecurringOccurrence.open_bills_due(family, dates, series: shared_recurring_transactions).each_with_object(Hash.new(0.to_d)) do |occurrence, sums|+ category_id = occurrence.recurring_transaction.category_id+ sums[parent_ids[category_id] || category_id] += occurrence.remaining_spending_money.exchange_to(family.currency).amount+ rescue Money::ConversionError+ next+ endendenddiff --git a/app/models/recurring_allocation.rb b/app/models/recurring_allocation.rbindex fc1d3ae51c..a779df6603 100644--- a/app/models/recurring_allocation.rb+++ b/app/models/recurring_allocation.rb@@ -28,6 +28,18 @@ class RecurringAllocation < ApplicationRecordbefore_validation :default_paid_on+ # Confirmed payments of the family's bills. Transfers to liabilities are+ # not spending and stay out, as do tombstones of ended series (a deleted or+ # dismissed bill), which the Allocator also ignores so the entry can be+ # matched again.+ scope :to_family_bills, ->(family) {+ confirmed+ .joins(recurring_occurrence: :recurring_transaction)+ .merge(RecurringTransaction.outflows)+ .where(recurring_transactions: { family_id: family.id })+ .where.not(recurring_transactions: { status: "ended" })+ }+privatedef currency_matches_occurrencereturn if recurring_occurrence.nil? || currency == recurring_occurrence.currencydiff --git a/app/models/recurring_occurrence.rb b/app/models/recurring_occurrence.rbindex fc6a36287e..0ae058c373 100644--- a/app/models/recurring_occurrence.rb+++ b/app/models/recurring_occurrence.rb@@ -34,6 +34,60 @@ class RecurringOccurrence < ApplicationRecordscope :closed, -> { where.not(status: :scheduled) }scope :due_between, ->(from, to) { where(due_on: from..to) }+ # The family's open bill occurrences due within `dates`, with their confirmed+ # allocation sums and their series' spending shares loaded in grouped+ # queries so remaining_spending_money on each row issues none. `series`+ # narrows the bills read, e.g. to those the whole family may see.+ def self.open_bills_due(family, dates, series: RecurringTransaction.all)+ occurrences = open_status+ .joins(:recurring_transaction)+ .merge(RecurringTransaction.bills)+ .merge(series)+ .where(recurring_transactions: { family_id: family.id })+ .where(due_on: dates)+ .includes(:recurring_transaction)+ .to_a++ sums = RecurringAllocation.confirmed+ .where(recurring_occurrence_id: occurrences.map(&:id))+ .group(:recurring_occurrence_id)+ .sum(:allocated_amount)+ shares = spending_shares(family, occurrences.map(&:recurring_transaction_id).uniq)+ occurrences.each do |occurrence|+ occurrence.cached_confirmed_allocated = sums.fetch(occurrence.id, 0)+ occurrence.spending_share = shares.fetch(occurrence.recurring_transaction_id, 1)+ end+ end++ # The part of each series' charge that is spending, by series id, for the+ # series whose charges get split: a mortgage instalment split into its+ # interest and a transfer of the principal to the loan is spending only for+ # the interest. Read off the series' latest split charge, as its children+ # that count as spending over the charge: the family's reported kinds+ # (Family#analytics_excluded_kinds, so a contribution to an investment+ # account counts only when the family counts investing as spending, as in+ # IncomeStatement::Totals) and not excluded. Series never split are absent:+ # all spending.+ def self.spending_shares(family, series_ids)+ latest_splits = RecurringAllocation.confirmed+ .joins(:recurring_occurrence, :entry)+ .where(recurring_occurrences: { recurring_transaction_id: series_ids })+ .where(entry_id: Entry.where.not(parent_entry_id: nil).select(:parent_entry_id))+ .order("recurring_occurrences.recurring_transaction_id", "entries.date DESC", "entries.id DESC")+ .pluck(Arel.sql("DISTINCT ON (recurring_occurrences.recurring_transaction_id) recurring_occurrences.recurring_transaction_id"),+ "entries.id", "entries.amount")+ return {} if latest_splits.empty?++ spent = Entry.where(parent_entry_id: latest_splits.map(&:second), excluded: false, entryable_type: "Transaction")+ .where(entryable_id: Transaction.where.not(kind: family.analytics_excluded_kinds).select(:id))+ .group(:parent_entry_id)+ .sum(:amount)++ latest_splits.each_with_object({}) do |(series_id, entry_id, amount), shares|+ shares[series_id] = (spent.fetch(entry_id, 0) / amount).clamp(0, 1) if amount.positive?+ end+ end+# The amount this occurrence expects, resolving NULL through the series'# amount strategy, which is what lets a price edit update every open# occurrence with no sweep. `series_amount` overrides what the series says it@@ -88,6 +142,15 @@ class RecurringOccurrence < ApplicationRecordMoney.new(remaining_amount, currency)end+ attr_writer :spending_share++ # The part of remaining_amount that will be spending: all of it, unless the+ # series' charges get split (see .spending_shares).+ def remaining_spending_money+ share = @spending_share || self.class.spending_shares(family, [ recurring_transaction_id ]).fetch(recurring_transaction_id, 1)+ Money.new((remaining_amount * share).round(Money::Currency.new(currency).default_precision), currency)+ end+# Exact sum, not tolerance: $1,850 allocated against $2,000 rent is# partially paid with $150 remaining, always.def partially_paid?diff --git a/app/models/recurring_transaction.rb b/app/models/recurring_transaction.rbindex 4aa5c98115..ff36f24306 100644--- a/app/models/recurring_transaction.rb+++ b/app/models/recurring_transaction.rb@@ -355,7 +355,11 @@ class RecurringTransaction < ApplicationRecord# An active recurring expense you owe someone: transfers are internal moves and# income is not owed, so neither belongs on a list of things to pay. No minimum# amount, since any threshold is wrong in some currency; pause handles the rest.- scope :bills, -> { active.where(destination_account_id: nil).where("amount > 0") }+ scope :bills, -> { active.outflows }++ # Money leaving the family: not a transfer between its own accounts, and not+ # income.+ scope :outflows, -> { where(destination_account_id: nil).where(arel_table[:amount].gt(0)) }# Everything the Bills page owes an answer for: expense bills and# subscriptions, PLUS recurring transfers into liability accounts -- adiff --git a/app/views/plans/_budget_card.html.erb b/app/views/plans/_budget_card.html.erbindex a28ce23757..c0161df81e 100644--- a/app/views/plans/_budget_card.html.erb+++ b/app/views/plans/_budget_card.html.erb@@ -13,7 +13,7 @@<% if budget.initialized? %><% if budget.available_to_spend.negative? %><%= render DS::Pill.new(label: t("reports.budget_performance.status.over"), tone: :error, marker: false, icon: "alert-circle") %>- <% elsif budget.percent_of_budget_spent >= 90 %>+ <% elsif budget.near_limit? %><%= render DS::Pill.new(label: t("reports.budget_performance.status.warning"), tone: :warning, marker: false, icon: "alert-triangle") %><% else %><%= render DS::Pill.new(label: t("reports.budget_performance.status.good"), tone: :success, marker: false, icon: "check-circle") %>diff --git a/config/locales/views/insights/ca.yml b/config/locales/views/insights/ca.ymlindex 520983db5d..556996e7f6 100644--- a/config/locales/views/insights/ca.yml+++ b/config/locales/views/insights/ca.yml@@ -43,7 +43,7 @@ ca:other: Últims %{count} diesdate_range: Del %{from} al %{to}figures:- vs_previous: vs. el mes anterior+ vs_previous_three_months: vs. els tres mesos anteriorstoday: avuion_pace: al ritme actualof_budget: del pressupost@@ -59,7 +59,7 @@ ca:cash_flow_warning: Revisa les transaccions recurrentsnet_worth_milestone: Veure l'informe de patrimoni netsubscription_audit: Revisa les transaccions recurrents- savings_rate_change: Veure les transaccions d'aquell mes+ savings_rate_change: Veure les transaccions d'aquells mesosidle_cash: Ves al comptebudget: Veure el pressupostmaintained_goal_depleted: Veure la reserva@@ -74,8 +74,8 @@ ca:maintained_goal_depleted: '%{goal} ha baixat per sota del seu nivell'subscription_audit: '%{name} encara està actiu?'savings_rate_change:- up: La teva taxa d'estalvi ha millorat a %{month}- down: La teva taxa d'estalvi ha baixat a %{month}+ up: La teva taxa d'estalvi ha millorat en els darrers tres mesos+ down: La teva taxa d'estalvi ha baixat en els darrers tres mesosidle_cash: Efectiu inactiu a %{account}budget_at_risk:one: Una categoria del teu pressupost requereix atenció@@ -92,9 +92,9 @@ ca:maintained_goal_depleted: '%{goal} té %{saved} dels %{target} que ha de mantenir. Hi falten %{missing}.'subscription_audit: '%{name} (%{amount}) no ha aparegut des que s''esperava el %{expected_on}. Potser s''ha cancel·lat o el càrrec s''ha mogut de data.'savings_rate_change:- up: A %{month} vas estalviar el %{current_rate}% dels teus ingressos, %{change_pp} punts percentuals més que el %{previous_rate}% del mes anterior.- down: A %{month} vas estalviar el %{current_rate}% dels teus ingressos, %{change_pp} punts percentuals menys que el %{previous_rate}% del mes anterior.- down_negative: 'A %{month} vas gastar més del que vas ingressar: la teva taxa d''estalvi va baixar al %{current_rate}%, des del %{previous_rate}% del mes anterior.'+ up: Entre %{from_month} i %{to_month} la teva taxa d'estalvi sobre els teus ingressos mensuals habituals va ser del %{current_rate}%, %{change_pp} punts percentuals més que el %{previous_rate}% dels tres mesos anteriors.+ down: Entre %{from_month} i %{to_month} la teva taxa d'estalvi sobre els teus ingressos mensuals habituals va ser del %{current_rate}%, %{change_pp} punts percentuals menys que el %{previous_rate}% dels tres mesos anteriors.+ down_negative: "Entre %{from_month} i %{to_month} vas gastar més del que vas ingressar: la teva taxa d'estalvi va baixar al %{current_rate}%, des del %{previous_rate}% dels tres mesos anteriors."idle_cash: '%{account} té %{balance} sense cap moviment en els últims %{idle_days} dies.'budget_at_risk:over: '%{categories} han superat el pressupost aquest mes. Fins ara has fet servir el %{budget_spent_pct}% del teu pressupost total.'diff --git a/config/locales/views/insights/de.yml b/config/locales/views/insights/de.ymlindex 250a5daf60..0316261328 100644--- a/config/locales/views/insights/de.yml+++ b/config/locales/views/insights/de.yml@@ -10,7 +10,7 @@ de:idle_cash: Zum Kontomaintained_goal_depleted: Rücklage ansehennet_worth_milestone: Bericht zum Nettovermögen ansehen- savings_rate_change: Transaktionen dieses Monats ansehen+ savings_rate_change: Transaktionen dieser Monate ansehenspending_anomaly: Transaktionen zu %{category} ansehensubscription_audit: Wiederkehrende Buchungen prüfencard:@@ -47,7 +47,7 @@ de:of_budget: vom Budgeton_pace: hochgerechnettoday: heute- vs_previous: vs. Vormonat+ vs_previous_three_months: vs. die drei Monate davorindex:empty:description: Insights erscheinen hier, sobald in deinen Konten genug passiert ist. Sie werden jede Nacht aktualisiert.@@ -78,9 +78,9 @@ de:maintained_goal_depleted: "Für %{goal} sind %{saved} von %{target} zurückgelegt. Bis zum Zielstand fehlen %{missing}."net_worth_milestone: Dein Nettovermögen hat %{milestone} überschritten und liegt jetzt bei %{net_worth}.savings_rate_change:- down: Du hast im %{month} %{current_rate} % deiner Einnahmen gespart, %{change_pp} Prozentpunkte weniger als die %{previous_rate} % im Monat davor.- down_negative: 'Du hast im %{month} mehr ausgegeben als eingenommen: Deine Sparquote fiel auf %{current_rate} %, nach %{previous_rate} % im Monat davor.'- up: Du hast im %{month} %{current_rate} % deiner Einnahmen gespart, %{change_pp} Prozentpunkte mehr als die %{previous_rate} % im Monat davor.+ down: Von %{from_month} bis %{to_month} lag deine Sparquote, gemessen an deinen üblichen Monatseinnahmen, bei %{current_rate} %, %{change_pp} Prozentpunkte weniger als die %{previous_rate} % in den drei Monaten davor.+ down_negative: "Von %{from_month} bis %{to_month} hast du mehr ausgegeben als eingenommen: Deine Sparquote fiel auf %{current_rate} %, nach %{previous_rate} % in den drei Monaten davor."+ up: Von %{from_month} bis %{to_month} lag deine Sparquote, gemessen an deinen üblichen Monatseinnahmen, bei %{current_rate} %, %{change_pp} Prozentpunkte mehr als die %{previous_rate} % in den drei Monaten davor.spending_anomaly:above: Hochgerechnet gibst du diesen Monat %{projected_spend} für %{category} aus, rund %{deviation_pct} % mehr als dein jüngster Monatsschnitt von %{baseline_spend}.below: Hochgerechnet gibst du diesen Monat %{projected_spend} für %{category} aus, rund %{deviation_pct} % weniger als dein jüngster Monatsschnitt von %{baseline_spend}.@@ -97,8 +97,8 @@ de:maintained_goal_depleted: "%{goal} liegt unter dem Zielstand"net_worth_milestone: 'Meilenstein beim Nettovermögen: %{milestone}'savings_rate_change:- down: Deine Sparquote ist im %{month} gesunken- up: Deine Sparquote ist im %{month} gestiegen+ down: Deine Sparquote ist in den letzten drei Monaten gesunken+ up: Deine Sparquote ist in den letzten drei Monaten gestiegenspending_anomaly:above: Deine Ausgaben für %{category} steigenbelow: Deine Ausgaben für %{category} sinkendiff --git a/config/locales/views/insights/en.yml b/config/locales/views/insights/en.ymlindex a359cb3395..6afe0b44fd 100644--- a/config/locales/views/insights/en.yml+++ b/config/locales/views/insights/en.yml@@ -56,7 +56,7 @@ en:other: Last %{count} daysdate_range: "%{from} to %{to}"figures:- vs_previous: vs prior month+ vs_previous_three_months: vs previous three monthstoday: todayon_pace: on paceof_budget: of budget@@ -72,7 +72,7 @@ en:cash_flow_warning: Review recurring transactionsnet_worth_milestone: View net worth reportsubscription_audit: Review recurring transactions- savings_rate_change: View that month's transactions+ savings_rate_change: View those months' transactionsidle_cash: Go to accountbudget: View budgetmaintained_goal_depleted: View reserve@@ -88,8 +88,8 @@ en:maintained_goal_depleted: "%{goal} has dropped below its level"subscription_audit: "Is %{name} still active?"savings_rate_change:- up: Your savings rate improved in %{month}- down: Your savings rate dropped in %{month}+ up: Your savings rate improved over the last three months+ down: Your savings rate dropped over the last three monthsidle_cash: Idle cash in %{account}budget_at_risk:one: One category needs attention in your budget@@ -109,9 +109,9 @@ en:maintained_goal_depleted: "%{goal} holds %{saved} of the %{target} it is meant to keep. It is %{missing} short."subscription_audit: "%{name} (%{amount}) hasn't appeared since it was expected on %{expected_on}. It may have been cancelled, or the charge may have moved."savings_rate_change:- up: You saved %{current_rate}% of your income in %{month}, up %{change_pp} percentage points from %{previous_rate}% the month before.- 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."+ up: From %{from_month} to %{to_month} your savings rate against your typical monthly income was %{current_rate}%, up %{change_pp} percentage points from %{previous_rate}% in the three months before.+ down: From %{from_month} to %{to_month} your savings rate against your typical monthly income was %{current_rate}%, down %{change_pp} percentage points from %{previous_rate}% in the three months before.+ down_negative: "From %{from_month} to %{to_month} you spent more than you earned: your savings rate fell to %{current_rate}%, from %{previous_rate}% in the three months 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."diff --git a/config/locales/views/insights/es.yml b/config/locales/views/insights/es.ymlindex 68704a2099..2645515b57 100644--- a/config/locales/views/insights/es.yml+++ b/config/locales/views/insights/es.yml@@ -56,7 +56,7 @@ es:other: Últimos %{count} díasdate_range: "%{from} a %{to}"figures:- vs_previous: frente al mes anterior+ vs_previous_three_months: frente a los tres meses anteriorestoday: hoyon_pace: al ritmo previstoof_budget: del presupuesto@@ -72,7 +72,7 @@ es:cash_flow_warning: Revisar transacciones recurrentesnet_worth_milestone: Ver informe de patrimonio netosubscription_audit: Revisar transacciones recurrentes- savings_rate_change: Ver transacciones de ese mes+ savings_rate_change: Ver las transacciones de esos mesesidle_cash: Ir a la cuentabudget: Ver presupuestomaintained_goal_depleted: Ver reserva@@ -88,8 +88,8 @@ es:maintained_goal_depleted: "%{goal} está por debajo del saldo que debe mantener"subscription_audit: "¿%{name} sigue activa?"savings_rate_change:- up: Tu tasa de ahorro mejoró en %{month}- down: Tu tasa de ahorro bajó en %{month}+ up: Tu tasa de ahorro mejoró en los últimos tres meses+ down: Tu tasa de ahorro bajó en los últimos tres mesesidle_cash: Efectivo inactivo en %{account}budget_at_risk:one: Una categoría necesita atención en tu presupuesto@@ -109,9 +109,9 @@ es:maintained_goal_depleted: "%{goal} tiene %{saved} de los %{target} que debe mantener. Le faltan %{missing}."subscription_audit: "%{name} (%{amount}) no aparece desde que se esperaba el %{expected_on}. Puede haberse cancelado o el cargo puede haber cambiado de fecha."savings_rate_change:- up: Ahorraste el %{current_rate}% de tus ingresos en %{month}, %{change_pp} puntos porcentuales más que el %{previous_rate}% del mes anterior.- down: Ahorraste el %{current_rate}% de tus ingresos en %{month}, %{change_pp} puntos porcentuales menos que el %{previous_rate}% del mes anterior.- down_negative: "Gastaste más de lo que ingresaste en %{month}: tu tasa de ahorro cayó al %{current_rate}%, desde el %{previous_rate}% del mes anterior."+ up: De %{from_month} a %{to_month} tu tasa de ahorro sobre tus ingresos mensuales habituales fue del %{current_rate}%, %{change_pp} puntos porcentuales más que el %{previous_rate}% de los tres meses anteriores.+ down: De %{from_month} a %{to_month} tu tasa de ahorro sobre tus ingresos mensuales habituales fue del %{current_rate}%, %{change_pp} puntos porcentuales menos que el %{previous_rate}% de los tres meses anteriores.+ down_negative: "De %{from_month} a %{to_month} gastaste más de lo que ingresaste: tu tasa de ahorro cayó al %{current_rate}%, desde el %{previous_rate}% de los tres meses anteriores."idle_cash: "%{account} tiene %{balance} sin actividad en los últimos %{idle_days} días."budget_at_risk:over: "%{categories} superaron el presupuesto este mes. Has usado el %{budget_spent_pct}% de tu presupuesto total hasta ahora."diff --git a/config/locales/views/insights/fr.yml b/config/locales/views/insights/fr.ymlindex cebc127fc5..d808861d46 100644--- a/config/locales/views/insights/fr.yml+++ b/config/locales/views/insights/fr.yml@@ -10,7 +10,7 @@ fr:idle_cash: Aller au comptemaintained_goal_depleted: Voir la réservenet_worth_milestone: Voir le rapport de patrimoine net- savings_rate_change: Voir les transactions de ce mois+ savings_rate_change: Voir les transactions de ces moisspending_anomaly: Voir les transactions de %{category}subscription_audit: Vérifier les transactions récurrentescard:@@ -37,7 +37,7 @@ fr:of_budget: du budgeton_pace: au rythme actueltoday: aujourd'hui- vs_previous: vs mois précédent+ vs_previous_three_months: vs les trois mois précédentsindex:empty:description: Les analyses apparaissent ici dès qu'il y a suffisamment d'activité@@ -78,14 +78,9 @@ fr:net_worth_milestone: Votre patrimoine net a franchi %{milestone} et s'élèvedésormais à %{net_worth}.savings_rate_change:- down: Vous avez épargné %{current_rate}% de vos revenus en %{month}, soit- %{change_pp} points de pourcentage de moins que %{previous_rate}% le mois- précédent.- down_negative: "Vous avez dépensé plus que vous n'avez gagné en %{month}- : votre taux d'épargne est tombé à %{current_rate}%, contre %{previous_rate}%- le mois précédent."- up: Vous avez épargné %{current_rate}% de vos revenus en %{month}, soit %{change_pp}- points de pourcentage de plus que %{previous_rate}% le mois précédent.+ down: Entre %{from_month} et %{to_month}, votre taux d'épargne rapporté à vos revenus mensuels habituels était de %{current_rate}%, soit %{change_pp} points de pourcentage de moins que les %{previous_rate}% des trois mois précédents.+ down_negative: "Entre %{from_month} et %{to_month}, vous avez dépensé plus que vous n'avez gagné : votre taux d'épargne est tombé à %{current_rate}%, contre %{previous_rate}% les trois mois précédents."+ up: Entre %{from_month} et %{to_month}, votre taux d'épargne rapporté à vos revenus mensuels habituels était de %{current_rate}%, soit %{change_pp} points de pourcentage de plus que les %{previous_rate}% des trois mois précédents.spending_anomaly:above: Vous êtes en voie de dépenser %{projected_spend} pour %{category}ce mois-ci, soit environ %{deviation_pct}% de plus que votre moyenne mensuelle@@ -108,8 +103,8 @@ fr:idle_cash: Liquidités inactives sur %{account}net_worth_milestone: "Étape de patrimoine net : %{milestone}"savings_rate_change:- down: Votre taux d'épargne a baissé en %{month}- up: Votre taux d'épargne s'est amélioré en %{month}+ down: Votre taux d'épargne a baissé sur les trois derniers mois+ up: Votre taux d'épargne s'est amélioré sur les trois derniers moisspending_anomaly:above: Les dépenses de %{category} sont en haussebelow: Les dépenses de %{category} sont en baissediff --git a/config/locales/views/insights/id.yml b/config/locales/views/insights/id.ymlindex 2975a87e93..1cd034eed7 100644--- a/config/locales/views/insights/id.yml+++ b/config/locales/views/insights/id.yml@@ -55,7 +55,7 @@ id:other: "%{count} hari terakhir"date_range: "%{from} hingga %{to}"figures:- vs_previous: vs bulan sebelumnya+ vs_previous_three_months: vs tiga bulan sebelumnyatoday: hari inion_pace: sesuai perkiraanof_budget: dari anggaran@@ -71,7 +71,7 @@ id:cash_flow_warning: Tinjau transaksi berulangnet_worth_milestone: Lihat laporan kekayaan bersihsubscription_audit: Tinjau transaksi berulang- savings_rate_change: Lihat transaksi bulan tersebut+ savings_rate_change: Lihat transaksi bulan-bulan tersebutidle_cash: Buka rekeningbudget: Lihat anggaranmaintained_goal_depleted: Lihat dana cadangan@@ -86,8 +86,8 @@ id:maintained_goal_depleted: "%{goal} turun di bawah target batasnya"subscription_audit: "Apakah %{name} masih aktif?"savings_rate_change:- up: Tingkat tabungan Anda meningkat pada %{month}- down: Tingkat tabungan Anda menurun pada %{month}+ up: Tingkat tabungan Anda meningkat dalam tiga bulan terakhir+ down: Tingkat tabungan Anda menurun dalam tiga bulan terakhiridle_cash: Kas menganggur di %{account}budget_at_risk:one: Satu kategori perlu perhatian dalam anggaran Anda@@ -104,9 +104,9 @@ id:maintained_goal_depleted: "%{goal} saat ini memiliki %{saved} dari %{target} yang seharusnya dipertahankan. Kurang %{missing} dari target."subscription_audit: "%{name} (%{amount}) belum muncul sejak jatuh tempo pada %{expected_on}. Langganan mungkin telah dibatalkan, atau tanggal tagihan telah bergeser."savings_rate_change:- up: Anda menabung %{current_rate}% dari pendapatan Anda pada %{month}, naik %{change_pp} poin persentase dari %{previous_rate}% pada bulan sebelumnya.- down: Anda menabung %{current_rate}% dari pendapatan Anda pada %{month}, turun %{change_pp} poin persentase dari %{previous_rate}% pada bulan sebelumnya.- down_negative: "Pengeluaran Anda melebihi pendapatan pada %{month}: tingkat tabungan Anda turun menjadi %{current_rate}%, dari %{previous_rate}% pada bulan sebelumnya."+ up: Dari %{from_month} hingga %{to_month} tingkat tabungan Anda terhadap pendapatan bulanan biasa Anda adalah %{current_rate}%, naik %{change_pp} poin persentase dari %{previous_rate}% pada tiga bulan sebelumnya.+ down: Dari %{from_month} hingga %{to_month} tingkat tabungan Anda terhadap pendapatan bulanan biasa Anda adalah %{current_rate}%, turun %{change_pp} poin persentase dari %{previous_rate}% pada tiga bulan sebelumnya.+ down_negative: "Dari %{from_month} hingga %{to_month} pengeluaran Anda melebihi pendapatan: tingkat tabungan Anda turun menjadi %{current_rate}%, dari %{previous_rate}% pada tiga bulan sebelumnya."idle_cash: "%{account} memiliki saldo %{balance} tanpa aktivitas dalam %{idle_days} hari terakhir."budget_at_risk:over: "%{categories} melebihi anggaran bulan ini. Anda telah menggunakan %{budget_spent_pct}% dari total anggaran sejauh ini."diff --git a/config/locales/views/insights/it.yml b/config/locales/views/insights/it.ymlindex 71072f4dc2..5b1a8c577b 100644--- a/config/locales/views/insights/it.yml+++ b/config/locales/views/insights/it.yml@@ -43,7 +43,7 @@ it:date_range: "%{from} - %{to}"figures:need_attention: richiedono attenzione- vs_previous: rispetto al mese precedente+ vs_previous_three_months: rispetto ai tre mesi precedentitoday: oggion_pace: in lineaof_budget: del budget@@ -58,7 +58,7 @@ it:cash_flow_warning: Controlla le transazioni ricorrentinet_worth_milestone: Vedi il report sul patrimonio nettosubscription_audit: Controlla le transazioni ricorrenti- savings_rate_change: Vedi le transazioni di quel mese+ savings_rate_change: Vedi le transazioni di quei mesiidle_cash: Vai al contobudget: Vedi il budgettitles:@@ -71,8 +71,8 @@ it:net_worth_milestone: "Traguardo del patrimonio netto: %{milestone}"subscription_audit: "%{name} è ancora attivo?"savings_rate_change:- up: Il tuo tasso di risparmio è migliorato in %{month}- down: Il tuo tasso di risparmio è diminuito in %{month}+ up: Il tuo tasso di risparmio è migliorato negli ultimi tre mesi+ down: Il tuo tasso di risparmio è diminuito negli ultimi tre mesiidle_cash: Liquidità inutilizzata in %{account}budget_at_risk:one: Una categoria del tuo budget richiede attenzione@@ -88,9 +88,9 @@ it:net_worth_milestone: "Il tuo patrimonio netto ha superato %{milestone} e ora è pari a %{net_worth}."subscription_audit: "%{name} (%{amount}) non è comparso dalla data prevista, %{expected_on}. Potrebbe essere stato annullato oppure l'addebito potrebbe essere stato spostato."savings_rate_change:- up: "In %{month} hai risparmiato il %{current_rate}% delle tue entrate, %{change_pp} punti percentuali in più rispetto al %{previous_rate}% del mese precedente."- down: "In %{month} hai risparmiato il %{current_rate}% delle tue entrate, %{change_pp} punti percentuali in meno rispetto al %{previous_rate}% del mese precedente."- down_negative: "In %{month} hai speso più di quanto hai guadagnato: il tuo tasso di risparmio è sceso al %{current_rate}%, dal %{previous_rate}% del mese precedente."+ up: Da %{from_month} a %{to_month} il tuo tasso di risparmio sulle tue entrate mensili abituali è stato del %{current_rate}%, %{change_pp} punti percentuali in più rispetto al %{previous_rate}% dei tre mesi precedenti.+ down: Da %{from_month} a %{to_month} il tuo tasso di risparmio sulle tue entrate mensili abituali è stato del %{current_rate}%, %{change_pp} punti percentuali in meno rispetto al %{previous_rate}% dei tre mesi precedenti.+ down_negative: "Da %{from_month} a %{to_month} hai speso più di quanto hai guadagnato: il tuo tasso di risparmio è sceso al %{current_rate}%, dal %{previous_rate}% dei tre mesi precedenti."idle_cash: "%{account} contiene %{balance} senza attività negli ultimi %{idle_days} giorni."budget_at_risk:over: "%{categories} hanno superato il budget questo mese. Finora hai usato il %{budget_spent_pct}% del budget totale."diff --git a/config/locales/views/insights/nl.yml b/config/locales/views/insights/nl.ymlindex 48ffa7eb53..7c9d8e1f80 100644--- a/config/locales/views/insights/nl.yml+++ b/config/locales/views/insights/nl.yml@@ -46,7 +46,7 @@ nl:other: "Afgelopen %{count} dagen"date_range: "%{from} t/m %{to}"figures:- vs_previous: "t.o.v. vorige maand"+ vs_previous_three_months: "t.o.v. de drie maanden daarvoor"today: "vandaag"on_pace: "verwacht"of_budget: "van budget"@@ -62,7 +62,7 @@ nl:cash_flow_warning: "Terugkerende transacties bekijken"net_worth_milestone: "Rapport netto vermogen bekijken"subscription_audit: "Terugkerende transacties bekijken"- savings_rate_change: "Transacties van die maand bekijken"+ savings_rate_change: Transacties van die maanden bekijkenidle_cash: "Naar account"budget: "Budget bekijken"maintained_goal_depleted: "Reserve bekijken"@@ -77,8 +77,8 @@ nl:maintained_goal_depleted: "%{goal} is onder het streefniveau gezakt"subscription_audit: "Is %{name} nog actief?"savings_rate_change:- up: "Uw spaarpercentage is gestegen in %{month}"- down: "Uw spaarpercentage is gedaald in %{month}"+ up: Uw spaarpercentage is de afgelopen drie maanden gestegen+ down: Uw spaarpercentage is de afgelopen drie maanden gedaaldidle_cash: "Ongebruikt geld op %{account}"budget_at_risk:one: "Eén categorie in uw budget vraagt aandacht"@@ -95,9 +95,9 @@ nl:maintained_goal_depleted: "%{goal} bevat %{saved} van de %{target} die het moet aanhouden. Er ontbreekt %{missing}."subscription_audit: "%{name} (%{amount}) is niet meer verschenen sinds de verwachte datum %{expected_on}. Mogelijk is het opgezegd, of is de afschrijving verschoven."savings_rate_change:- up: "U heeft in %{month} %{current_rate}% van uw inkomsten gespaard, %{change_pp} procentpunt meer dan de %{previous_rate}% van de maand ervoor."- down: "U heeft in %{month} %{current_rate}% van uw inkomsten gespaard, %{change_pp} procentpunt minder dan de %{previous_rate}% van de maand ervoor."- down_negative: "U heeft in %{month} meer uitgegeven dan verdiend: uw spaarpercentage daalde naar %{current_rate}%, van %{previous_rate}% de maand ervoor."+ up: Van %{from_month} tot en met %{to_month} was uw spaarquote ten opzichte van uw gebruikelijke maandinkomen %{current_rate}%, %{change_pp} procentpunt meer dan de %{previous_rate}% in de drie maanden daarvoor.+ down: Van %{from_month} tot en met %{to_month} was uw spaarquote ten opzichte van uw gebruikelijke maandinkomen %{current_rate}%, %{change_pp} procentpunt minder dan de %{previous_rate}% in de drie maanden daarvoor.+ down_negative: "Van %{from_month} tot en met %{to_month} heeft u meer uitgegeven dan verdiend: uw spaarpercentage daalde naar %{current_rate}%, van %{previous_rate}% in de drie maanden daarvoor."idle_cash: "%{account} bevat %{balance} zonder activiteit in de afgelopen %{idle_days} dagen."budget_at_risk:over: "%{categories} gingen deze maand over het budget. U heeft tot nu toe %{budget_spent_pct}% van uw totale budget gebruikt."diff --git a/config/locales/views/insights/pl.yml b/config/locales/views/insights/pl.ymlindex 163d76dfc1..f20ac72623 100644--- a/config/locales/views/insights/pl.yml+++ b/config/locales/views/insights/pl.yml@@ -7,7 +7,7 @@ pl:idle_cash: Przejdź do kontamaintained_goal_depleted: Zobacz rezerwęnet_worth_milestone: Zobacz raport wartości netto- savings_rate_change: Zobacz transakcje z tego miesiąca+ savings_rate_change: Zobacz transakcje z tych miesięcyspending_anomaly: Zobacz transakcje %{category}subscription_audit: Przejrzyj cykliczne transakcjecard:@@ -37,7 +37,7 @@ pl:of_budget: z budżetuon_pace: zgodnie z tempemtoday: dzisiaj- vs_previous: vs. poprzedni miesiąc+ vs_previous_three_months: vs. poprzednie trzy miesiąceindex:empty:description: Analizy pojawią się tutaj, gdy na kontach będzie wystarczająco@@ -84,13 +84,9 @@ pl:net_worth_milestone: Twoja wartość netto przekroczyła %{milestone} i wynositeraz %{net_worth}.savings_rate_change:- down: Zaoszczędziłeś %{current_rate}% swojego dochodu w ciągu %{month}, spadek- o %{change_pp} punktów procentowych z %{previous_rate}% w poprzednim miesiącu.- down_negative: 'Wydałeś więcej niż zarobiłeś w ciągu %{month}: Twoja stopa- oszczędności spadła do %{current_rate}% z %{previous_rate}% w poprzednim- miesiącu.'- up: Zaoszczędziłeś %{current_rate}% swojego dochodu w ciągu %{month}, wzrost- o %{change_pp} punktów procentowych z %{previous_rate}% w poprzednim miesiącu.+ down: Od %{from_month} do %{to_month} Twoja stopa oszczędności względem zwykłego miesięcznego dochodu wyniosła %{current_rate}%, o %{change_pp} punktów procentowych mniej niż %{previous_rate}% w poprzednich trzech miesiącach.+ down_negative: "Od %{from_month} do %{to_month} wydałeś więcej, niż zarobiłeś: Twoja stopa oszczędności spadła do %{current_rate}% z %{previous_rate}% w poprzednich trzech miesiącach."+ up: Od %{from_month} do %{to_month} Twoja stopa oszczędności względem zwykłego miesięcznego dochodu wyniosła %{current_rate}%, o %{change_pp} punktów procentowych więcej niż %{previous_rate}% w poprzednich trzech miesiącach.spending_anomaly:above: Jesteś na dobrej drodze, aby wydać %{projected_spend} na %{category}w tym miesiącu, około %{deviation_pct}% więcej niż Twoja średnia miesięczna@@ -114,8 +110,8 @@ pl:maintained_goal_depleted: "%{goal} spadł poniżej swojego poziomu"net_worth_milestone: 'Kamień milowy wartości netto: %{milestone}'savings_rate_change:- down: Twoja stopa oszczędności spadła w ciągu %{month}- up: Twoja stopa oszczędności poprawiła się w ciągu %{month}+ down: Twoja stopa oszczędności spadła w ostatnich trzech miesiącach+ up: Twoja stopa oszczędności poprawiła się w ostatnich trzech miesiącachspending_anomaly:above: Wydatki w kategorii %{category} rosnąbelow: Wydatki w kategorii %{category} spadajądiff --git a/config/locales/views/insights/pt-PT.yml b/config/locales/views/insights/pt-PT.ymlindex 98768b8da5..634cfe49bf 100644--- a/config/locales/views/insights/pt-PT.yml+++ b/config/locales/views/insights/pt-PT.yml@@ -43,7 +43,7 @@ pt-PT:other: Últimos %{count} diasdate_range: "%{from} a %{to}"figures:- vs_previous: vs. mês anterior+ vs_previous_three_months: vs. os três meses anteriorestoday: hojeon_pace: dentro do ritmoof_budget: do orçamento@@ -59,7 +59,7 @@ pt-PT:cash_flow_warning: Rever transações recorrentesnet_worth_milestone: Ver relatório de património líquidosubscription_audit: Rever transações recorrentes- savings_rate_change: Ver as transações desse mês+ savings_rate_change: Ver as transações desses mesesidle_cash: Ir para a contabudget: Ver orçamentomaintained_goal_depleted: Ver reserva@@ -74,8 +74,8 @@ pt-PT:maintained_goal_depleted: "%{goal} caiu abaixo do seu nível"subscription_audit: "%{name} ainda está ativa?"savings_rate_change:- up: A sua taxa de poupança melhorou em %{month}- down: A sua taxa de poupança caiu em %{month}+ up: A sua taxa de poupança melhorou nos últimos três meses+ down: A sua taxa de poupança caiu nos últimos três mesesidle_cash: Dinheiro parado em %{account}budget_at_risk:one: Uma categoria precisa de atenção no seu orçamento@@ -92,9 +92,9 @@ pt-PT:maintained_goal_depleted: "%{goal} detém %{saved} do objetivo de %{target} que deve manter. Faltam %{missing}."subscription_audit: "%{name} (%{amount}) não aparece desde a data prevista de %{expected_on}. Pode ter sido cancelada, ou o cobrança pode ter mudado."savings_rate_change:- up: Poupa %{current_rate}% do seu rendimento em %{month}, mais %{change_pp} pontos percentuais do que os %{previous_rate}% do mês anterior.- down: Poupa %{current_rate}% do seu rendimento em %{month}, menos %{change_pp} pontos percentuais do que os %{previous_rate}% do mês anterior.- down_negative: "Gastou mais do que ganhou em %{month}: a sua taxa de poupança caiu para %{current_rate}%, face aos %{previous_rate}% do mês anterior."+ up: De %{from_month} a %{to_month} a sua taxa de poupança face ao seu rendimento mensal habitual foi de %{current_rate}%, mais %{change_pp} pontos percentuais do que os %{previous_rate}% dos três meses anteriores.+ down: De %{from_month} a %{to_month} a sua taxa de poupança face ao seu rendimento mensal habitual foi de %{current_rate}%, menos %{change_pp} pontos percentuais do que os %{previous_rate}% dos três meses anteriores.+ down_negative: "De %{from_month} a %{to_month} gastou mais do que ganhou: a sua taxa de poupança caiu para %{current_rate}%, face aos %{previous_rate}% dos três meses anteriores."idle_cash: "%{account} detém %{balance} sem atividade nos últimos %{idle_days} dias."budget_at_risk:over: "%{categories} excederam o orçamento este mês. Utilizou %{budget_spent_pct}% do orçamento total até agora."diff --git a/config/locales/views/insights/ru.yml b/config/locales/views/insights/ru.ymlindex 6127e5919f..2ee97f09b8 100644--- a/config/locales/views/insights/ru.yml+++ b/config/locales/views/insights/ru.yml@@ -47,7 +47,7 @@ ru:other: Последние %{count} дняdate_range: '%{from} – %{to}'figures:- vs_previous: к прошлому месяцу+ vs_previous_three_months: к трём предыдущим месяцамtoday: сегодняon_pace: по текущему темпуof_budget: от бюджета@@ -67,7 +67,7 @@ ru:cash_flow_warning: Проверить регулярные операцииnet_worth_milestone: Открыть отчёт о чистой стоимостиsubscription_audit: Проверить регулярные операции- savings_rate_change: Операции за тот месяц+ savings_rate_change: Операции за эти месяцыidle_cash: Перейти к счётуbudget: Открыть бюджетmaintained_goal_depleted: Открыть резерв@@ -82,8 +82,8 @@ ru:maintained_goal_depleted: Резерв «%{goal}» опустился ниже целевого уровняsubscription_audit: Подписка %{name} всё ещё активна?savings_rate_change:- up: Норма сбережений выросла (%{month})- down: Норма сбережений снизилась (%{month})+ up: Норма сбережений за последние три месяца выросла+ down: Норма сбережений за последние три месяца снизиласьidle_cash: Неработающие деньги на счёте %{account}budget_at_risk:one: '%{count} категория бюджета требует внимания'@@ -102,9 +102,9 @@ ru:maintained_goal_depleted: В резерве «%{goal}» %{saved} из %{target}, которые он должен поддерживать. Не хватает %{missing}.subscription_audit: Платёж %{name} (%{amount}) не поступал с ожидаемой даты %{expected_on}. Возможно, подписка отменена или дата списания изменилась.savings_rate_change:- up: Вы сберегли %{current_rate}% дохода (%{month}) — на %{change_pp} п. п. больше, чем %{previous_rate}% месяцем ранее.- down: Вы сберегли %{current_rate}% дохода (%{month}) — на %{change_pp} п. п. меньше, чем %{previous_rate}% месяцем ранее.- down_negative: 'Вы потратили больше, чем заработали (%{month}): норма сбережений упала до %{current_rate}% с %{previous_rate}% месяцем ранее.'+ up: За период %{from_month} — %{to_month} норма сбережений от вашего обычного месячного дохода составила %{current_rate}% — на %{change_pp} п. п. больше, чем %{previous_rate}% за три месяца до этого.+ down: За период %{from_month} — %{to_month} норма сбережений от вашего обычного месячного дохода составила %{current_rate}% — на %{change_pp} п. п. меньше, чем %{previous_rate}% за три месяца до этого.+ down_negative: "За период %{from_month} — %{to_month} вы потратили больше, чем заработали: норма сбережений упала до %{current_rate}% с %{previous_rate}% за три месяца до этого."idle_cash: На счёте %{account} лежит %{balance} без движения последние %{idle_days} дн.budget_at_risk:over: 'Превышен бюджет в этом месяце: %{categories}. Вы уже использовали %{budget_spent_pct}% общего бюджета.'diff --git a/config/locales/views/insights/tr.yml b/config/locales/views/insights/tr.ymlindex 5c0f75dbd0..db65fc6bcb 100644--- a/config/locales/views/insights/tr.yml+++ b/config/locales/views/insights/tr.yml@@ -9,7 +9,7 @@ tr:cash_flow_warning: Yinelenen işlemleri inceleidle_cash: Hesaba gitnet_worth_milestone: Net değer raporunu görüntüle- savings_rate_change: O ayın işlemlerini görüntüle+ savings_rate_change: Bu ayların işlemlerini görüntülespending_anomaly: "%{category} işlemlerini görüntüle"subscription_audit: Yinelenen işlemleri incelemaintained_goal_depleted: Rezervi görüntüle@@ -35,7 +35,7 @@ tr:of_budget: bütçeninon_pace: bu tempodatoday: bugün- vs_previous: önceki aya göre+ vs_previous_three_months: önceki üç aya göreneed_attention: dikkat gerektiriyorindex:empty:@@ -75,12 +75,9 @@ tr:net_worth_milestone: Net değeriniz %{milestone} sınırını geçti ve şu anda %{net_worth}seviyesinde.savings_rate_change:- down: "%{month} ayında gelirinizin %{current_rate}%'ini biriktirdiniz, bu- önceki aydaki %{previous_rate}%'den %{change_pp} puan düşüş anlamına geliyor."- down_negative: "%{month} ayında kazandığınızdan daha fazla harcadınız: tasarruf- oranınız önceki aydaki %{previous_rate}%'den %{current_rate}%'e düştü."- up: "%{month} ayında gelirinizin %{current_rate}%'ini biriktirdiniz, bu önceki- aydaki %{previous_rate}%'den %{change_pp} puan artış anlamına geliyor."+ down: "%{from_month}–%{to_month} döneminde olağan aylık gelirinize göre tasarruf oranınız %{current_rate}% oldu; bu, önceki üç aydaki %{previous_rate}%'e göre %{change_pp} puan daha az."+ down_negative: "%{from_month}–%{to_month} döneminde kazandığınızdan fazla harcadınız: tasarruf oranınız önceki üç aydaki %{previous_rate}%'den %{current_rate}%'e düştü."+ up: "%{from_month}–%{to_month} döneminde olağan aylık gelirinize göre tasarruf oranınız %{current_rate}% oldu; bu, önceki üç aydaki %{previous_rate}%'e göre %{change_pp} puan daha fazla."spending_anomaly:above: Bu ay %{category} kategorisinde %{projected_spend} harcama temposundasınız;bu, son aylık ortalamanız olan %{baseline_spend}'den yaklaşık %{deviation_pct}%@@ -102,8 +99,8 @@ tr:idle_cash: "%{account} hesabında hareketsiz nakit"net_worth_milestone: 'Net değer kilometre taşı: %{milestone}'savings_rate_change:- down: Tasarruf oranınız %{month} ayında düştü- up: Tasarruf oranınız %{month} ayında iyileşti+ down: Tasarruf oranınız son üç ayda düştü+ up: Tasarruf oranınız son üç ayda iyileştispending_anomaly:above: "%{category} harcamaları artış eğiliminde"below: "%{category} harcamaları azalış eğiliminde"diff --git a/config/locales/views/insights/uk.yml b/config/locales/views/insights/uk.ymlindex 5f0842e7dc..ac12a340c7 100644--- a/config/locales/views/insights/uk.yml+++ b/config/locales/views/insights/uk.yml@@ -49,7 +49,7 @@ uk:many: Останні %{count} днівdate_range: "З %{from} по %{to}"figures:- vs_previous: порівняно з попереднім місяцем+ vs_previous_three_months: порівняно з попередніми трьома місяцямиtoday: сьогодніon_pace: за планомof_budget: бюджету@@ -69,7 +69,7 @@ uk:cash_flow_warning: Переглянути повторювані транзакціїnet_worth_milestone: Переглянути звіт про чистий капіталsubscription_audit: Переглянути повторювані транзакції- savings_rate_change: Переглянути транзакції за цей місяць+ savings_rate_change: Переглянути транзакції за ці місяціidle_cash: Перейти до рахункуbudget: Переглянути бюджетmaintained_goal_depleted: Переглянути резерв@@ -83,8 +83,8 @@ uk:net_worth_milestone: "Рубіж чистого капіталу: %{milestone}"subscription_audit: "Чи %{name} все ще активний?"savings_rate_change:- up: Ваш рівень заощаджень покращився в %{month}- down: Ваш рівень заощаджень знизився в %{month}+ up: Ваш рівень заощаджень за останні три місяці покращився+ down: Ваш рівень заощаджень за останні три місяці знизивсяidle_cash: Незадіяні кошти на %{account}budget_at_risk:one: "%{count} категорія потребує уваги у вашому бюджеті"@@ -103,9 +103,9 @@ uk:net_worth_milestone: Ваш чистий капітал перевищив %{milestone} і тепер становить %{net_worth}.subscription_audit: "%{name} (%{amount}) не з'являвся з моменту очікуваної дати %{expected_on}. Можливо, його було скасовано, або платіж перенесено."savings_rate_change:- up: Ви заощадили %{current_rate}% свого доходу в %{month}, що на %{change_pp} процентних пунктів більше, ніж %{previous_rate}% попереднього місяця.- down: Ви заощадили %{current_rate}% свого доходу в %{month}, що на %{change_pp} процентних пунктів менше, ніж %{previous_rate}% попереднього місяця.- down_negative: "Ви витратили більше, ніж заробили в %{month}: ваш рівень заощаджень впав до %{current_rate}%, з %{previous_rate}% попереднього місяця."+ up: За період %{from_month} — %{to_month} ваш рівень заощаджень щодо звичайного місячного доходу становив %{current_rate}%, що на %{change_pp} процентних пунктів більше, ніж %{previous_rate}% за попередні три місяці.+ down: За період %{from_month} — %{to_month} ваш рівень заощаджень щодо звичайного місячного доходу становив %{current_rate}%, що на %{change_pp} процентних пунктів менше, ніж %{previous_rate}% за попередні три місяці.+ down_negative: "За період %{from_month} — %{to_month} ви витратили більше, ніж заробили: ваш рівень заощаджень впав до %{current_rate}% з %{previous_rate}% за попередні три місяці."idle_cash: "%{account} містить %{balance} без активності протягом останніх %{idle_days} днів."budget_at_risk:over: "%{categories} перевищили бюджет цього місяця. Ви використали %{budget_spent_pct}% свого загального бюджету наразі."diff --git a/config/locales/views/insights/zh-CN.yml b/config/locales/views/insights/zh-CN.ymlindex 88f684d4b4..0a4ba064dd 100644--- a/config/locales/views/insights/zh-CN.yml+++ b/config/locales/views/insights/zh-CN.yml@@ -55,7 +55,7 @@ zh-CN:other: "过去 %{count} 天"date_range: "%{from} 至 %{to}"figures:- vs_previous: 相较上月+ vs_previous_three_months: 相较之前三个月today: 今天on_pace: 按目前进度of_budget: 占预算@@ -71,7 +71,7 @@ zh-CN:cash_flow_warning: 查看循环交易net_worth_milestone: 查看净资产报告subscription_audit: 查看循环交易- savings_rate_change: 查看该月份交易+ savings_rate_change: 查看这几个月份的交易idle_cash: 前往账户budget: 查看预算maintained_goal_depleted: 查看储备金@@ -86,8 +86,8 @@ zh-CN:maintained_goal_depleted: "%{goal} 已跌破设定水平"subscription_audit: "%{name} 仍在订阅中吗?"savings_rate_change:- up: "您在 %{month} 的储蓄率有所提高"- down: "您在 %{month} 的储蓄率有所下降"+ up: 您近三个月的储蓄率有所提高+ down: 您近三个月的储蓄率有所下降idle_cash: "%{account} 中有闲置现金"budget_at_risk:one: 预算中有一个分类需要注意@@ -104,9 +104,9 @@ zh-CN:maintained_goal_depleted: "%{goal} 目前持有 %{saved},低于预定目标 %{target},尚缺 %{missing}。"subscription_audit: "%{name}(%{amount})自预期的 %{expected_on} 后未再出现。可能已被取消,或扣款日期有所变动。"savings_rate_change:- up: "您在 %{month} 存下了收入的 %{current_rate}%,比前一个月的 %{previous_rate}% 提高了 %{change_pp} 个百分点。"- down: "您在 %{month} 存下了收入的 %{current_rate}%,比前一个月的 %{previous_rate}% 降低了 %{change_pp} 个百分点。"- down_negative: "您在 %{month} 的支出超过了收入:储蓄率从前一个月的 %{previous_rate}% 降至 %{current_rate}%。"+ up: "%{from_month}至%{to_month},按您平常的月收入计算,储蓄率为 %{current_rate}%,比之前三个月的 %{previous_rate}% 提高了 %{change_pp} 个百分点。"+ down: "%{from_month}至%{to_month},按您平常的月收入计算,储蓄率为 %{current_rate}%,比之前三个月的 %{previous_rate}% 降低了 %{change_pp} 个百分点。"+ down_negative: "%{from_month}至%{to_month},您的支出超过了收入:储蓄率从之前三个月的 %{previous_rate}% 降至 %{current_rate}%。"idle_cash: "%{account} 拥有 %{balance},且在过去 %{idle_days} 天内没有任何交易活动。"budget_at_risk:over: "%{categories} 本月已超出预算。您目前已使用总预算的 %{budget_spent_pct}%。"diff --git a/config/locales/views/insights/zh-TW.yml b/config/locales/views/insights/zh-TW.ymlindex b2f65fbf94..d5c7df46ae 100644--- a/config/locales/views/insights/zh-TW.yml+++ b/config/locales/views/insights/zh-TW.yml@@ -43,7 +43,7 @@ zh-TW:other: 過去 %{count} 天date_range: '%{from} 至 %{to}'figures:- vs_previous: 相較上月+ vs_previous_three_months: 相較之前三個月today: 今天on_pace: 依目前進度of_budget: 佔預算@@ -59,7 +59,7 @@ zh-TW:cash_flow_warning: 檢視定期交易net_worth_milestone: 查看淨資產報表subscription_audit: 檢視定期交易- savings_rate_change: 查看該月份的交易+ savings_rate_change: 查看這幾個月的交易idle_cash: 前往帳戶budget: 查看預算titles:@@ -72,8 +72,8 @@ zh-TW:net_worth_milestone: 淨資產里程碑:%{milestone}subscription_audit: '%{name} 還在使用中嗎?'savings_rate_change:- up: 您在%{month}的儲蓄率提高了- down: 您在%{month}的儲蓄率下降了+ up: 您近三個月的儲蓄率提高了+ down: 您近三個月的儲蓄率下降了idle_cash: '%{account} 有閒置現金'budget_at_risk:one: 您的預算中有一個分類需要注意@@ -89,9 +89,9 @@ zh-TW:net_worth_milestone: 您的淨資產已越過 %{milestone},目前為 %{net_worth}。subscription_audit: '%{name}(%{amount})自預期的 %{expected_on} 之後就沒有再出現。可能已經取消,或是扣款時間改變了。'savings_rate_change:- up: 您在%{month}存下了收入的 %{current_rate}%,比前一個月的 %{previous_rate}% 高出 %{change_pp} 個百分點。- down: 您在%{month}存下了收入的 %{current_rate}%,比前一個月的 %{previous_rate}% 低了 %{change_pp} 個百分點。- down_negative: 您在%{month}的支出超過收入:儲蓄率從前一個月的 %{previous_rate}% 降到 %{current_rate}%。+ up: "%{from_month}至%{to_month},以您平常的月收入計算,儲蓄率為 %{current_rate}%,比之前三個月的 %{previous_rate}% 高出 %{change_pp} 個百分點。"+ down: "%{from_month}至%{to_month},以您平常的月收入計算,儲蓄率為 %{current_rate}%,比之前三個月的 %{previous_rate}% 低了 %{change_pp} 個百分點。"+ down_negative: "%{from_month}至%{to_month},您的支出超過收入:儲蓄率從之前三個月的 %{previous_rate}% 降到 %{current_rate}%。"idle_cash: '%{account} 有 %{balance},且在過去 %{idle_days} 天內沒有任何活動。'budget_at_risk:over: '%{categories} 這個月已超出預算。您目前已使用總預算的 %{budget_spent_pct}%。'diff --git a/test/controllers/budgets_controller_test.rb b/test/controllers/budgets_controller_test.rbindex 8ea76fadde..12fea05575 100644--- a/test/controllers/budgets_controller_test.rb+++ b/test/controllers/budgets_controller_test.rb@@ -1,6 +1,8 @@require "test_helper"class BudgetsControllerTest < ActionDispatch::IntegrationTest+ include EntriesTestHelper+setup do@user = users(:family_admin)sign_in @user@@ -88,6 +90,34 @@ class BudgetsControllerTest < ActionDispatch::IntegrationTestassert_select "a[href=?]", budget_budget_category_path(budget, shared_budget_category), count: 0end+ # The pill, the bar and the remaining figure all read near_limit?, so a line+ # filled by bills paid early stays green on every one of them.+ test "show keeps a line filled by bills out of the near-limit state" do+ budget_category = gym_line++ get budget_url(Budget.date_to_param(Date.current))++ assert_response :success+ assert_select "a[href=?]", budget_budget_category_path(budget_category.budget, budget_category) do+ assert_select "*", text: I18n.t("reports.budget_performance.status.good")+ assert_select ".bg-warning, .text-yellow-500", count: 0+ end+ end++ test "show marks a line near its limit by spending outside bills" do+ budget_category = gym_line+ create_transaction(category: budget_category.category, amount: 9, date: Date.current)++ get budget_url(Budget.date_to_param(Date.current))++ assert_response :success+ assert_select "a[href=?]", budget_budget_category_path(budget_category.budget, budget_category) do+ assert_select "*", text: I18n.t("reports.budget_performance.status.warning")+ assert_select ".bg-warning", count: 1+ assert_select ".text-yellow-500", count: 1+ end+ end+test "show displays ring-fenced child carry on the parent card" dobudget = budgets(:one)parent_category = budget.family.categories.create!(name: "Parent rollover card", color: "#4da568")@@ -169,6 +199,15 @@ class BudgetsControllerTest < ActionDispatch::IntegrationTestassert_select free_row.parent, "dd.text-2xl", count: 1assert_select free_row, "dd.text-2xl", count: 1end++ private+ # A 100 line whose 90 bill was paid today: 90% spent, none of it outside bills.+ def gym_line+ budget = budgets(:one)+ category = budget.family.categories.create!(name: "Gym line presentation", color: "#4da568")+ pay_bill(create_bill(category: category, amount: 90, name: "Gym"), date: Date.current)+ budget.budget_categories.create!(category: category, budgeted_spending: 100, currency: "USD")+ endendclass BudgetsControllerSharingTest < ActionDispatch::IntegrationTestdiff --git a/test/controllers/plans_controller_test.rb b/test/controllers/plans_controller_test.rbindex 6c098dacb2..250894f4b9 100644--- a/test/controllers/plans_controller_test.rb+++ b/test/controllers/plans_controller_test.rb@@ -37,6 +37,15 @@ class PlansControllerTest < ActionDispatch::IntegrationTest"the depleted reserve's bar stayed neutral"end+ # The budget pill follows the same near-limit rule as each budget line.+ test "the budget card keeps a budget filled by bills out of the near-limit state" do+ assert_equal I18n.t("reports.budget_performance.status.good"), budget_pill(bills_paid: 950)+ end++ test "the budget card marks a budget near its limit by spending outside bills" do+ assert_equal I18n.t("reports.budget_performance.status.warning"), budget_pill(bills_paid: 0)+ end+test "goals missing an exchange rate share one warning line" do2.times do |i|account = @user.family.accounts.create!(name: "Euro reserve #{i}", accountable: Depository.new,@@ -109,6 +118,20 @@ class PlansControllerTest < ActionDispatch::IntegrationTestassert_match I18n.t("plans.budget_card.empty_body"), response.bodyassert_select "a[href=?]", edit_budget_path(Budget.date_to_param(Date.current))end++ private+ # The budget card's status pill for a 1,000 budget with 950 spent.+ def budget_pill(bills_paid:)+ budgets(:one).update!(budgeted_spending: 1_000)+ Budget.any_instance.stubs(:actual_spending).returns(950)+ Budget.any_instance.stubs(:bills_paid).returns(bills_paid)++ get plan_url++ assert_response :success+ labels = %w[good warning over].map { |status| I18n.t("reports.budget_performance.status.#{status}") }+ css_select("span[title]").map { |span| span["title"] }.find { |title| labels.include?(title) }+ endendclass PlansControllerHouseholdSwitchingTest < ActionDispatch::IntegrationTestdiff --git a/test/helpers/insights_helper_test.rb b/test/helpers/insights_helper_test.rbindex 68a059d667..6b5a551b2d 100644--- a/test/helpers/insights_helper_test.rb+++ b/test/helpers/insights_helper_test.rb@@ -69,6 +69,20 @@ class InsightsHelperTest < ActionView::TestCaseassert_equal "Savings rate · June", insight_meta_line(insight)end+ # The savings-rate window covers whole months. Read on the 1st, its range+ # ends yesterday and used to come out as "Last 91 days".+ test "meta line names a range of whole months by its first and last month" do+ travel_to Date.new(2026, 11, 1) do+ insight = build_insight(+ "savings_rate_change",+ period_start: Date.new(2026, 8, 1),+ period_end: Date.new(2026, 10, 31)+ )++ assert_equal "Savings rate · August to October", insight_meta_line(insight)+ end+ end+test "meta line labels a forward-looking window as next N days" dotravel_to Date.new(2026, 8, 1) doinsight = build_insight(@@ -132,6 +146,19 @@ class InsightsHelperTest < ActionView::TestCaseassert_equal "need attention", captionend+ # The generator compares two three-month windows, so the caption names that+ # basis rather than a single prior month.+ test "savings rate change is captioned against the previous three months" do+ insight = build_insight("savings_rate_change",+ facts: { "change_pp" => "4.2" },+ metadata: { "current_rate" => 18.0, "previous_rate" => 13.8 })++ figure, caption = insight_key_figure(insight)++ assert_equal "+4.2 pp", figure+ assert_equal "vs previous three months", caption+ end+test "budget on track still leads with overall consumption" doinsight = build_insight("budget_on_track", facts: { "budget_spent_pct" => 62 })diff --git a/test/models/assistant/function/get_budget_test.rb b/test/models/assistant/function/get_budget_test.rbindex baba3142cc..08f23f15e0 100644--- a/test/models/assistant/function/get_budget_test.rb+++ b/test/models/assistant/function/get_budget_test.rb@@ -152,6 +152,15 @@ class Assistant::Function::GetBudgetTest < ActiveSupport::TestCaseassert_equal "over_budget", food[:status]end+ test "category status is near_limit when spending outside bills fills the line" do+ assert_equal "near_limit", food_status(spent: 95, bills_paid: 0)+ end++ # Bills paid early fill the line without using anything up.+ test "category status is on_track when bills fill the line" do+ assert_equal "on_track", food_status(spent: 95, bills_paid: 95)+ end+test "suggested_daily_spending omitted on non-current months" dotarget = Date.current.beginning_of_month << 1result = @function.call("month" => target.strftime("%Y-%m"))@@ -182,4 +191,14 @@ class Assistant::Function::GetBudgetTest < ActiveSupport::TestCaseassert totals.key?(key), "totals should include #{key}"endend++ private+ def food_status(spent:, bills_paid:)+ budget = Budget.find_or_bootstrap(@family, start_date: Date.current.beginning_of_month, user: @user)+ budget.budget_categories.find { |bc| bc.category == categories(:food_and_drink) }.update!(budgeted_spending: 100)+ BudgetCategory.any_instance.stubs(:actual_spending).returns(spent)+ BudgetCategory.any_instance.stubs(:bills_paid).returns(bills_paid)++ @function.call({})[:months].first[:categories].find { |c| c[:name] == "Food & Drink" }[:status]+ endenddiff --git a/test/models/budget_category_test.rb b/test/models/budget_category_test.rbindex 759d9cf590..b2a038488c 100644--- a/test/models/budget_category_test.rb+++ b/test/models/budget_category_test.rb@@ -1,6 +1,8 @@require "test_helper"class BudgetCategoryTest < ActiveSupport::TestCase+ include EntriesTestHelper+setup do@family = families(:dylan_family)@budget = budgets(:one)@@ -115,6 +117,20 @@ class BudgetCategoryTest < ActiveSupport::TestCaseassert_equal 0, @parent_budget_category.bills_reserved_unconvertible_countend+ # Only the interest of a mortgage instalment lands in the bill's category;+ # the principal is a transfer to the loan. The latest split charge says how+ # much of the next one will be spending.+ test "bills_reserved counts only the spending share of a bill whose charges are split" do+ mortgage = create_bill(category: @parent_category, amount: 1_000, name: "Mortgage")+ split_payment(pay_bill(mortgage, date: @budget.start_date - 2.months),+ { amount: 500, category: @parent_category }, { amount: 500, kind: "funds_movement" })+ split_payment(pay_bill(mortgage, date: @budget.start_date - 1.month),+ { amount: 600, category: @parent_category }, { amount: 400, kind: "funds_movement" })+ expect_bill(mortgage, due_on: @budget.start_date + 3)++ assert_equal 600, @parent_budget_category.bills_reserved.amount+ end+test "bills_reserved loads the budget's obligations once for all its categories" dobill = @family.recurring_transactions.create!(name: "Groceries plan", account: accounts(:depository), amount: 120,@@ -141,6 +157,66 @@ class BudgetCategoryTest < ActiveSupport::TestCaseassert_equal 0, reserved[@parent_category.id]end+ # Compared against actual_spending, which counts a parent's subcategories,+ # so a parent's figure includes theirs too. Payments outside the budget+ # period belong to another month.+ test "bills_paid sums the period's bill payments, subcategories included" do+ rent = create_bill(category: @parent_category, amount: 30, name: "Parent bill")+ dinner_club = create_bill(category: @subcategory_with_limit, amount: 120, name: "Dinner club")+ pay_bill(rent, date: @budget.start_date)+ pay_bill(rent, date: @budget.start_date - 1.month)+ pay_bill(dinner_club, date: @budget.start_date + 1)++ assert_equal 150, @parent_budget_category.bills_paid+ assert_equal 120, @subcategory_with_limit_bc.bills_paid+ assert_equal 0, @subcategory_inheriting_bc.bills_paid+ end++ test "bills_paid loads the budget's payments once for all its categories" do+ pay_bill(create_bill(category: @subcategory_with_limit, amount: 120), date: @budget.start_date)++ first, *rest = Budget.find(@budget.id).budget_categories.to_a+ first.bills_paid++ assert_queries_count(0) do+ rest.each(&:bills_paid)+ end+ end++ # Fixed charges that land early fill the envelope without using anything+ # up, so near_limit? only counts spending outside bills.+ test "near_limit? ignores a line filled by bills already paid" do+ pay_bill(create_bill(category: @parent_category, amount: 950, name: "Rent"), date: Date.current)++ assert_operator @parent_budget_category.percent_of_budget_spent, :>=, BudgetCategory::NEAR_LIMIT_PERCENT+ assert_not @parent_budget_category.near_limit?+ end++ # The payment is split into its interest, spent in the line, and a transfer+ # of the principal; the interest is the bill's.+ test "near_limit? ignores a line filled by a bill paid with a split charge" do+ mortgage = create_bill(category: @parent_category, amount: 1_400, name: "Mortgage")+ split_payment(pay_bill(mortgage, date: Date.current),+ { amount: 950, category: @parent_category }, { amount: 450, kind: "funds_movement" })++ assert_equal 950, @parent_budget_category.bills_paid+ assert_not @parent_budget_category.near_limit?+ end++ # Rent takes 950 of 1,000; 45 of other spending uses 90% of the 50 it leaves.+ test "near_limit? warns when spending outside bills uses up what bills leave" do+ pay_bill(create_bill(category: @parent_category, amount: 950, name: "Rent"), date: Date.current)+ create_transaction(category: @parent_category, amount: 45, date: Date.current)++ assert @parent_budget_category.near_limit?+ end++ test "near_limit? warns about a line near its limit when it has no bills" do+ create_transaction(category: @parent_category, amount: 950, date: Date.current)++ assert @parent_budget_category.near_limit?+ end+test "subcategory with zero budget inherits from parent" doassert @subcategory_inheriting_bc.inherits_parent_budget?refute @subcategory_with_limit_bc.inherits_parent_budget?diff --git a/test/models/budget_test.rb b/test/models/budget_test.rbindex d1c9fe39bb..538762376d 100644--- a/test/models/budget_test.rb+++ b/test/models/budget_test.rb@@ -1,6 +1,8 @@require "test_helper"class BudgetTest < ActiveSupport::TestCase+ include EntriesTestHelper+setup do@family = families(:empty)end@@ -225,6 +227,63 @@ class BudgetTest < ActiveSupport::TestCase)end+ # The whole budget follows the rule its lines do: bills that fill it are+ # not a reason to warn. Three months back keeps the fixture entries out.+ test "near_limit? counts only spending outside bills" do+ today = (Date.current - 3.months).change(day: 15)+ category = @family.categories.create!(name: "Near limit budget", color: "#101010", lucide_icon: "circle")+ account = @family.accounts.create!(name: "Checking", currency: "USD", balance: 0, accountable: Depository.new)+ budget = @family.budgets.create!(start_date: today.beginning_of_month, end_date: today.end_of_month,+ budgeted_spending: 1_000, expected_income: 2_000, currency: "USD")+ budget.budget_categories.create!(category: category, budgeted_spending: 1_000, currency: "USD")++ travel_to today do+ pay_bill(create_bill(category: category, amount: 950, name: "Rent", account: account), date: today.change(day: 3))+ assert_operator budget.percent_of_budget_spent, :>=, 90+ assert_not budget.near_limit?++ create_transaction(category: category, account: account, amount: 45, date: today.change(day: 4))+ assert Budget.find(budget.id).near_limit?+ end+ end++ # A refund in the bill's category brings that line's spending to 50, so only+ # 50 of the budget's spending is bills; the 860 elsewhere fills what is left.+ test "near_limit? counts no more bills than a line's spending after refunds" do+ today = (Date.current - 3.months).change(day: 15)+ home, food = %w[Home Food].map { |name| @family.categories.create!(name: "Refund #{name}", color: "#101010", lucide_icon: "circle") }+ account = @family.accounts.create!(name: "Checking", currency: "USD", balance: 0, accountable: Depository.new)+ budget = @family.budgets.create!(start_date: today.beginning_of_month, end_date: today.end_of_month,+ budgeted_spending: 1_000, expected_income: 2_000, currency: "USD")+ [ home, food ].each { |category| budget.budget_categories.create!(category: category, budgeted_spending: 500, currency: "USD") }++ travel_to today do+ pay_bill(create_bill(category: home, amount: 950, name: "Insurance", account: account), date: today.change(day: 3))+ create_transaction(category: home, account: account, amount: -900, date: today.change(day: 4), name: "Insurance refund")+ create_transaction(category: food, account: account, amount: 860, date: today.change(day: 5))++ assert Budget.find(budget.id).near_limit?+ end+ end++ # Uncategorized spending is part of actual_spending, so a bill paid from+ # an uncategorized entry is part of the bills too.+ test "near_limit? counts uncategorized bill payments as bills" do+ today = (Date.current - 3.months).change(day: 15)+ category = @family.categories.create!(name: "Uncategorized bill", color: "#101010", lucide_icon: "circle")+ account = @family.accounts.create!(name: "Checking", currency: "USD", balance: 0, accountable: Depository.new)+ budget = @family.budgets.create!(start_date: today.beginning_of_month, end_date: today.end_of_month,+ budgeted_spending: 1_000, expected_income: 2_000, currency: "USD")++ travel_to today do+ pay_bill(create_bill(category: category, amount: 950, name: "Rent", account: account),+ date: today.change(day: 3), category: nil)++ assert_operator budget.percent_of_budget_spent, :>=, 90+ assert_not budget.near_limit?+ end+ end+test "to_donut_segments_json only includes top-level budget categories" dofamily = @familybudget = Budget.find_or_bootstrap(family, start_date: Date.current.beginning_of_month)diff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rbindex 89f0912f4a..bc1eeda369 100644--- a/test/models/income_statement_test.rb+++ b/test/models/income_statement_test.rb@@ -1180,6 +1180,88 @@ class IncomeStatementTest < ActiveSupport::TestCaseassert_equal 1, totals_query_callsend+ test "bill_expense_totals counts only the spending that paid bills, rolled into parents" do+ pay_bill(groceries_bill, date: Date.current)++ totals = bill_totals++ assert_equal 50, totals[@groceries_category.id]+ assert_equal 50, totals[@food_category.id]+ assert_equal 900 + 50, IncomeStatement.new(@family).expense_totals(period: Period.current_month)+ .category_totals.find { |ct| ct.category == @food_category }.total+ end++ test "bill_expense_totals counts a payment once however many occurrences it settles" do+ bill = groceries_bill+ entry = pay_bill(bill, date: Date.current)+ expect_bill(bill, due_on: Date.current + 1.day, amount: 10).allocations.create!(+ entry: entry, allocated_amount: 10, currency: "USD", source: "auto_matched"+ )++ assert_equal 50, bill_totals[@food_category.id]+ end++ # Totals are cached for the day and linking a payment doesn't touch its+ # entry, so the cache has to notice the allocation itself.+ test "bill_expense_totals follows payments linked and unlinked the same day" do+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)+ bill = groceries_bill+ entry = pay_bill(bill, date: Date.current)+ assert_equal 50, bill_totals[@food_category.id]++ allocation = RecurringAllocation.find_by!(entry: entry)+ allocation.destroy!+ assert_equal 0, bill_totals[@food_category.id]++ relinked = allocation.recurring_occurrence.allocations.create!(+ entry: entry, allocated_amount: 50, currency: "USD", source: "auto_matched", state: "suggested"+ )+ assert_equal 0, bill_totals[@food_category.id]++ relinked.update!(state: "confirmed", source: "user_confirmed")+ assert_equal 50, bill_totals[@food_category.id]+ end++ # The Allocator lets an entry be matched again once its bill was deleted or+ # dismissed; the tombstone must not count it a second time, or at all.+ test "bill_expense_totals ignores payments of ended bills" do+ bill = groceries_bill+ pay_bill(bill, date: Date.current)+ bill.update_columns(status: "ended")++ assert_equal 0, bill_totals[@food_category.id]+ end++ # A split payment is excluded and its children count in its place: the+ # expense parts in their own categories, the transfer part not at all.+ test "bill_expense_totals counts the spending parts of a split payment" do+ fees = @family.categories.create!(name: "Fees")+ split_payment(pay_bill(groceries_bill, date: Date.current),+ { amount: 30, category: @groceries_category },+ { amount: 15, category: fees },+ { amount: 5, kind: "funds_movement" })++ totals = bill_totals++ assert_equal 30, totals[@groceries_category.id]+ assert_equal 30, totals[@food_category.id]+ assert_equal 15, totals[fees.id]+ assert_equal 45, IncomeStatement.new(@family).bill_expense_totals(period: Period.current_month).total+ end++ # Mid-month, so the future-dated payment still falls inside the period.+ test "bill_expense_totals leaves out what expense_totals leaves out" do+ travel_to Date.current.beginning_of_month + 14.days do+ pay_bill(groceries_bill, date: Date.current).update!(excluded: true)+ pay_bill(create_bill(category: @groceries_category, amount: 60, name: "Future", account: @checking_account), date: Date.current + 1.day)+ hidden = @family.accounts.create!(name: "Hidden", currency: @family.currency, balance: 0,+ accountable: Depository.new, exclude_from_reports: true)+ pay_bill(create_bill(category: @groceries_category, amount: 70, name: "Hidden", account: hidden), date: Date.current)++ assert_equal 0, bill_totals[@food_category.id]+ end+ end+private# Adds a 250 grocery expense whose pending flag is +flag+ and asserts every# figure is the one without it: totals (Transaction.excluding_pending), the@@ -1199,4 +1281,13 @@ class IncomeStatementTest < ActiveSupport::TestCaseassert_equal 900.0, income_statement.avg_expense(interval: "month")assert_equal 900.0, income_statement.median_expense(interval: "month", category: @groceries_category)end++ def groceries_bill+ create_bill(category: @groceries_category, amount: 50, name: "Veg box", account: @checking_account)+ end++ def bill_totals+ IncomeStatement.new(@family).bill_expense_totals(period: Period.current_month)+ .category_totals.to_h { |ct| [ ct.category.id, ct.total ] }+ endenddiff --git a/test/models/insight/body_writer_test.rb b/test/models/insight/body_writer_test.rbindex ca8860947f..ba67c3be3c 100644--- a/test/models/insight/body_writer_test.rb+++ b/test/models/insight/body_writer_test.rb@@ -14,11 +14,34 @@ class Insight::BodyWriterTest < ActiveSupport::TestCaseassert_equal I18n.t("insights.templates.idle_cash", **generated_insight.facts.symbolize_keys), bodyend+ # In every locale that translates the template: a translation left on an+ # old interpolation would otherwise raise only for the users who read it.test "every template key interpolates with its generator's facts" doTEMPLATE_FACTS.each do |template_key, facts|- body = I18n.t!("insights.templates.#{template_key}", **facts)+ I18n.available_locales.each do |locale|+ key = "insights.templates.#{template_key}"+ next unless I18n.exists?(key, locale, fallback: false)- assert body.present?, "insights.templates.#{template_key} produced a blank body"+ body = I18n.t!(key, locale: locale, **facts)++ assert body.present?, "#{locale}: #{key} produced a blank body"+ end+ end+ end++ # A translation that drops a placeholder still interpolates, so it would+ # pass the test above while losing a figure from the sentence.+ test "translated savings-rate copy keeps the English placeholders" do+ %w[templates.savings_rate_change.up templates.savings_rate_change.down+ templates.savings_rate_change.down_negative titles.savings_rate_change.up+ titles.savings_rate_change.down].each do |key|+ expected = placeholders(I18n.t!("insights.#{key}", locale: :en))++ I18n.available_locales.each do |locale|+ next unless I18n.exists?("insights.#{key}", locale, fallback: false)++ assert_equal expected, placeholders(I18n.t!("insights.#{key}", locale: locale)), "#{locale}: insights.#{key}"+ endendend@@ -33,15 +56,19 @@ class Insight::BodyWriterTest < ActiveSupport::TestCase"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 },+ "savings_rate_change.up" => { from_month: "April", to_month: "June", current_rate: 32.5, previous_rate: 20.1, change_pp: 12.4 },+ "savings_rate_change.down" => { from_month: "April", to_month: "June", current_rate: "12.1", previous_rate: "45.2", change_pp: 33.1 },+ "savings_rate_change.down_negative" => { from_month: "April", to_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+ def placeholders(text)+ text.scan(/%\{(\w+)\}/).flatten.sort+ end+def generated_insight@generated_insight ||= Insight::Generator::GeneratedInsight.new(insight_type: "idle_cash",diff --git a/test/models/insight/generators/budget_insight_generator_test.rb b/test/models/insight/generators/budget_insight_generator_test.rbindex 5cd13e7d27..8e40870908 100644--- a/test/models/insight/generators/budget_insight_generator_test.rb+++ b/test/models/insight/generators/budget_insight_generator_test.rb@@ -5,8 +5,64 @@ class Insight::Generators::BudgetInsightGeneratorTest < ActiveSupport::TestCasesetup do@family = families(:dylan_family)+ @category = @family.categories.create!(name: "Budget Test Cat", color: "#101010", lucide_icon: "circle")+ # The current month's household budget, for the shared-accounts tests.@budget = budgets(:one)- @category = @family.categories.create!(name: "Budget Insight Cat", color: "#101010", lucide_icon: "circle")+ # Two months back so the fixture entries, dated in the real current month,+ # stay out of the budget. Day 6 is early: the month is far from half over.+ @today = (Date.current - 2.months).change(day: 6)+ @month = @today.beginning_of_month+ end++ # Fixed charges that land early fill the line on day 6, but nothing in it is+ # left to watch: the month's bills are paid and nothing else was spent.+ test "does not warn about a line filled by bills already paid" do+ budget_line(50)+ gym = create_bill(category: @category, amount: 45, name: "Gym", day: 3)+ medical = create_bill(category: @category, amount: 5, name: "Medical plan", day: 5)++ travel_to @today do+ pay_bill(gym, date: @month.change(day: 3))+ pay_bill(medical, date: @month.change(day: 5))++ assert_empty generate+ end+ end++ # Rent takes 800 of a 1,000 line; 100 of other spending leaves half of the+ # remaining 200 free. The line is at 90%, but not near its limit.+ test "does not warn when bills account for most of a line near its limit" do+ budget_line(1_000)+ rent = create_bill(category: @category, amount: 800, name: "Rent", day: 3)++ travel_to @today do+ pay_bill(rent, date: @month.change(day: 3))+ create_transaction(category: @category, amount: 100, date: @month.change(day: 4))++ assert_empty generate+ end+ end++ test "warns when spending outside bills uses up what the bills leave" do+ budget_line(1_000)+ rent = create_bill(category: @category, amount: 800, name: "Rent", day: 3)++ travel_to @today do+ pay_bill(rent, date: @month.change(day: 3))+ create_transaction(category: @category, amount: 185, date: @month.change(day: 4))++ assert_near_limit generate+ end+ end++ test "warns about a line near its limit when it has no bills" do+ budget_line(100)++ travel_to @today do+ create_transaction(category: @category, amount: 95, date: @month.change(day: 4))++ assert_near_limit generate+ endend# 95 of 100 spent would be "near the limit", but the spend sits on@@ -72,15 +128,32 @@ class Insight::Generators::BudgetInsightGeneratorTest < ActiveSupport::TestCaseendprivate- def budget_category(budget)- budget.budget_categories.create!(category: @category, budgeted_spending: 100, currency: "USD")+ def generate+ Insight::Generators::BudgetInsightGenerator.new(@family).generate+ end++ def generated_types+ generate.map(&:insight_type)enddef generated_digest- Insight::Generators::BudgetInsightGenerator.new(@family).generate.first.metadata[:accounts_digest]+ generate.first.metadata[:accounts_digest]end- def generated_types- Insight::Generators::BudgetInsightGenerator.new(@family).generate.map(&:insight_type)+ def budget_category(budget, amount = 100)+ budget.budget_categories.create!(category: @category, budgeted_spending: amount, currency: "USD")+ end++ def budget_line(amount)+ budget = @family.budgets.create!(+ start_date: @month, end_date: @month.end_of_month,+ budgeted_spending: amount, expected_income: amount * 2, currency: "USD"+ )+ budget_category(budget, amount)+ end++ def assert_near_limit(insights)+ assert_equal [ "budget_at_risk" ], insights.map(&:insight_type)+ assert_equal [ @category.id ], insights.first.metadata[:near_category_ids]endenddiff --git a/test/models/insight/generators/savings_rate_change_generator_test.rb b/test/models/insight/generators/savings_rate_change_generator_test.rbindex 704f0b2202..3a67673c9a 100644--- a/test/models/insight/generators/savings_rate_change_generator_test.rb+++ b/test/models/insight/generators/savings_rate_change_generator_test.rb@@ -5,29 +5,207 @@ class Insight::Generators::SavingsRateChangeGeneratorTest < ActiveSupport::TestCsetup do@family = families(:dylan_family)+ # Far enough back that the fixture entries, dated in the real current+ # month, fall outside both compared windows.+ @today = (Date.current - 7.months).change(day: 10)+ last_month = @today.beginning_of_month - 1.month+ # Oldest first: the previous window's three months, then the last three.+ @months = (0..5).map { |i| last_month - (5 - i).months }end- # Far enough back that the relative-date fixture entries fall after it.- def today- @today ||= (Date.current - 6.months).change(day: 15)+ test "compares the last three complete months with the three before" do+ travel_to @today do+ @months.first(3).each { |month| record(month, income: 5_000, spending: 4_000) }+ @months.last(3).each { |month| record(month, income: 5_000, spending: 3_000) }++ insight = generate.sole++ assert_equal "savings_rate_change.up", insight.template_key+ assert_equal({ current_rate: 40.0, previous_rate: 20.0 }, insight.metadata.except(:accounts_digest))+ assert_equal @months[3], insight.period_start+ assert_equal @months[5].end_of_month, insight.period_end+ assert_equal I18n.l(@months[3], format: "%B"), insight.facts[:from_month]+ assert_equal I18n.l(@months[5], format: "%B"), insight.facts[:to_month]+ assert_equal "savings_rate_change:v2:#{@months[5].strftime("%Y-%m")}", insight.dedup_key+ endend- # 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+ test "reports a drop into spending more than was earned" do+ travel_to @today do+ @months.first(3).each { |month| record(month, income: 5_000, spending: 4_000) }+ @months.last(3).each { |month| record(month, income: 5_000, spending: 5_500) }++ assert_equal [ "savings_rate_change.down_negative" ], generate.map(&:template_key)+ end+ end++ # A 5,000 salary paid on the 29th instead of the 1st gives one month two+ # salaries and the next none. Month against month that reads as a jump from+ # -33% to 50%; inside one window it changes nothing.+ test "does not report a paycheck that moved between months of the same window" do+ travel_to @today do+ @months.first(3).each { |month| record(month, income: 8_000, spending: 4_000) }+ record(@months[3], income: 13_000, spending: 4_000)+ record(@months[4], income: 3_000, spending: 4_000)+ record(@months[5], income: 8_000, spending: 4_000)++ assert_empty generate+ end+ end++ # Averaging the monthly rates would let one month whose pay landed+ # elsewhere (-279%) drag the earlier window down to about -68%, and report+ # a recovery of 88 points that never happened.+ test "does not average monthly rates" do+ travel_to @today do+ record(@months[0], income: 1_000, spending: 3_788)+ record(@months[1], income: 9_000, spending: 4_000)+ record(@months[2], income: 5_000, spending: 4_000)+ @months.last(3).each { |month| record(month, income: 5_000, spending: 4_000) }++ assert_empty generate+ end+ end- [ 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}")+ # A 5,000 salary normally paid on the 1st arrives once on the last day of the+ # month before. Run by run, that month enters the latest window (two+ # salaries in one month), then sits on the edge between the windows three+ # months later, then leaves through the earlier window three months after+ # that. None of those runs is a change in how the family saves.+ test "does not report a paycheck paid early, in any window position" do+ early = @months[3]+ months = (-6..5).map { |offset| early + offset.months }++ months.each do |month|+ salaries = if month == early - 1.month then 2 elsif month == early then 0 else 1 end+ record(month, income: 5_000 * salaries, spending: 4_000)+ end++ (0..6).each do |runs_later|+ travel_to((early + runs_later.months).change(day: 10)) do+ assert_empty generate, "#{runs_later} months after the early payday"end- create_transaction(amount: 400, date: last_month.change(day: 9), name: "private",+ end+ end++ test "reports a raise once the latest window earns it" do+ travel_to @today do+ @months.first(3).each { |month| record(month, income: 5_000, spending: 4_000) }+ @months.last(3).each { |month| record(month, income: 6_000, spending: 4_000) }++ assert_equal [ "savings_rate_change.up" ], generate.map(&:template_key)+ end+ end++ test "reports a drop in income" do+ travel_to @today do+ @months.first(3).each { |month| record(month, income: 5_000, spending: 4_000) }+ @months.last(3).each { |month| record(month, income: 4_500, spending: 4_000) }++ assert_equal [ "savings_rate_change.down" ], generate.map(&:template_key)+ end+ end++ # Spending is summed, not smoothed: a one-off 1,500 in a single month moves+ # the window's rate from 20% to 10%.+ test "reports a one-off rise in spending" do+ travel_to @today do+ @months.first(3).each { |month| record(month, income: 5_000, spending: 4_000) }+ record(@months[3], income: 5_000, spending: 5_500)+ @months.last(2).each { |month| record(month, income: 5_000, spending: 4_000) }++ assert_equal({ current_rate: 10.0, previous_rate: 20.0 }, generate.sole.metadata.except(:accounts_digest))+ end+ end++ # A bonus month lifts the window's real income above its spending while+ # the median-based rate is negative. "You spent more than you earned" would+ # be false; the plain "down" copy still reports the drop.+ test "says spending passed income only when the window's totals say so" do+ travel_to @today do+ @months.first(3).each { |month| record(month, income: 5_000, spending: 4_000) }+ record(@months[3], income: 2_000, spending: 4_000)+ record(@months[4], income: 2_000, spending: 4_000)+ record(@months[5], income: 12_000, spending: 4_000)++ assert_equal [ "savings_rate_change.down" ], generate.map(&:template_key)+ end+ end++ # The same window saved 25% of what came in, while the rate reads -100%:+ # the copy has to say the rate is measured against typical monthly income,+ # not that the family saved -100% of its income.+ test "names the typical-income basis of the rate it reports" do+ travel_to @today do+ @months.first(3).each { |month| record(month, income: 5_000, spending: 4_000) }+ record(@months[3], income: 2_000, spending: 4_000)+ record(@months[4], income: 2_000, spending: 4_000)+ record(@months[5], income: 12_000, spending: 4_000)++ body = Insight::BodyWriter.new.write(generate.sole)++ assert_includes body, "against your typical monthly income was −100.0%"+ assert_no_match(/of your income/, body)+ end+ end++ # With months starting on the 15th the window runs from the 15th to the+ # 14th, which month names alone would misreport.+ test "names a custom-month window by its dates" do+ @family.update!(month_start_day: 15)+ today = (Date.current - 7.months).change(day: 20)+ window_start = (today.change(day: 15) - 3.months)+ starts = (0..5).map { |i| window_start - 3.months + i.months }++ travel_to today do+ starts.first(3).each { |start| record(start, income: 5_000, spending: 4_000) }+ starts.last(3).each { |start| record(start, income: 5_000, spending: 3_000) }++ facts = generate.sole.facts++ assert_equal I18n.l(window_start, format: :short), facts[:from_month]+ assert_equal I18n.l(today.change(day: 14), format: :short), facts[:to_month]+ end+ end++ test "does not report without income in both windows" do+ travel_to @today do+ @months.last(3).each { |month| record(month, income: 5_000, spending: 3_000) }++ assert_empty generate+ end+ end++ # The generator passes no interpolation to the title, so a translation still+ # asking for one would show the raw placeholder to the users of that locale.+ test "titles need no interpolation in any locale" do+ I18n.available_locales.product(%w[up down]).each do |locale, direction|+ assert_no_match(/%\{/, I18n.t!("insights.titles.savings_rate_change.#{direction}", locale: locale), locale)+ end+ end++ # Both windows save half of a 1,000 monthly 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+ @months.each { |month| record(month, income: 1_000, spending: 500) }+ create_transaction(amount: 1_200, date: @months[5] + 8.days, name: "Private spend",account: accounts(:connected))- assert_empty Insight::Generators::SavingsRateChangeGenerator.new(@family).generate+ assert_empty generateendend++ private+ def generate+ Insight::Generators::SavingsRateChangeGenerator.new(@family).generate+ end++ # Pay on the month's first day, spending four days later.+ def record(month, income:, spending:)+ create_transaction(amount: -income, date: month + 1.day, name: "Pay #{month}") if income.positive?+ create_transaction(amount: spending, date: month + 4.days, name: "Spend #{month}")+ endenddiff --git a/test/models/insight/generators/spending_anomaly_generator_test.rb b/test/models/insight/generators/spending_anomaly_generator_test.rbindex aa1c89152b..5e768b5169 100644--- a/test/models/insight/generators/spending_anomaly_generator_test.rb+++ b/test/models/insight/generators/spending_anomaly_generator_test.rb@@ -2,6 +2,7 @@ require "test_helper"class Insight::Generators::SpendingAnomalyGeneratorTest < ActiveSupport::TestCaseinclude EntriesTestHelper+ include SqlQueryCapturesetup do@family = families(:dylan_family)@@ -10,17 +11,26 @@ class Insight::Generators::SpendingAnomalyGeneratorTest < ActiveSupport::TestCas# Anchor two months back so the relative-date fixture entries (always in the# real current month) can't leak into the baseline or current periods. Day 10- # gives 10 elapsed days, comfortably past MIN_ELAPSED_DAYS.+ # gives 10 elapsed days, comfortably past MIN_ELAPSED_DAYS. Tests that need a+ # different point in the month set @anchor_day before the first call.def anchor- @anchor ||= (Date.current - 2.months).change(day: 10)+ @anchor ||= (Date.current - 2.months).change(day: @anchor_day || 10)+ end++ def baseline_months+ (1..3).map { |i| month_start(i) }+ end++ def current_month+ anchor.beginning_of_monthenddef month_start(offset)(anchor.beginning_of_month - offset.months).beginning_of_monthend- def spend(month, total)- create_transaction(category: @category, amount: total, date: month.change(day: 3), name: "test #{month}")+ def spend(month, total, day: 3)+ create_transaction(category: @category, amount: total, date: month.change(day: day), name: "test #{month} #{day}")enddef generate@@ -68,4 +78,368 @@ class Insight::Generators::SpendingAnomalyGeneratorTest < ActiveSupport::TestCasassert_empty generateendend++ # Fixed charges that landed early (a gym fee and a medical plan, the same+ # every month) are already the whole month. Projecting them by pace doubled+ # them on day 15 and reported the category as trending up about 100%.+ test "does not project bills already paid this month" do+ @anchor_day = 15+ gym = create_bill(category: @category, amount: 45, name: "Gym", day: 3)+ medical = create_bill(category: @category, amount: 5, name: "Medical plan", day: 5)++ travel_to anchor do+ [ *baseline_months, current_month ].each do |month|+ pay_bill(gym, date: month.change(day: 3))+ pay_bill(medical, date: month.change(day: 5))+ end++ assert_empty generate+ end+ end++ # A bill still due this month is spending the month will have: it is added+ # at face value, so the projection, and the deviation, reflect it. Left out,+ # the category would read 52% below its average instead of 29%. The bill+ # sits in a subcategory and counts under its parent, as its payments do.+ test "counts a bill still due this month at face value" do+ insurance_category = @family.categories.create!(name: "Pace Test Insurance", parent: @category)+ rent = create_bill(category: @category, amount: 1_000, name: "Rent", day: 3)+ insurance = create_bill(category: insurance_category, amount: 500, name: "Insurance", day: 20)++ travel_to anchor do+ baseline_months.each do |month|+ pay_bill(rent, date: month.change(day: 3))+ pay_bill(insurance, date: month.change(day: 20))+ spend(month, 600, day: 12)+ end+ pay_bill(rent, date: current_month.change(day: 3))+ expect_bill(insurance, due_on: current_month.change(day: 20))++ insights = generate++ assert_equal 1, insights.size+ assert_equal "below", insights.first.metadata[:direction]+ assert_equal "medium", insights.first.priority+ assert_equal Money.new(1_500, "USD").format, insights.first.facts[:projected_spend]+ end+ end++ # The same month as above, but the insurance sits on `connected`, private+ # to family_admin. Its payments are out of the baseline, so its instalment+ # still due must stay out of the projection too: counted, it would lift the+ # month to 1,500 against a usual 1,600 and hide the drop.+ test "ignores a bill still due on an account private to one member" do+ rent = create_bill(category: @category, amount: 1_000, name: "Rent", day: 3)+ insurance = create_bill(category: @category, amount: 500, name: "Insurance", day: 20,+ account: accounts(:connected))++ travel_to anchor do+ baseline_months.each do |month|+ pay_bill(rent, date: month.change(day: 3))+ pay_bill(insurance, date: month.change(day: 20))+ spend(month, 600, day: 12)+ end+ pay_bill(rent, date: current_month.change(day: 3))+ expect_bill(insurance, due_on: current_month.change(day: 20))++ insights = generate++ assert_equal [ "below" ], insights.map { |insight| insight.metadata[:direction] }+ assert_equal Money.new(1_000, "USD").format, insights.first.facts[:projected_spend]+ end+ end++ # A mortgage instalment split into its interest, spent in the category, and+ # a transfer of the principal to the loan: the interest is a paid bill.+ test "does not project a bill paid with a split charge" do+ mortgage = split_mortgage_bill++ travel_to anchor do+ [ *baseline_months, current_month ].each { |month| pay_split_instalment(mortgage, month) }+ baseline_months.each { |month| spend(month, 300, day: 12) }+ spend(current_month, 100, day: 5)++ assert_empty generate+ end+ end++ # Of the instalment still due only its interest will be spending, as in the+ # last split charge; counted whole it doubled the projection.+ test "counts only the spending share of a split bill still due" do+ mortgage = split_mortgage_bill++ travel_to anchor do+ baseline_months.each do |month|+ pay_split_instalment(mortgage, month)+ spend(month, 300, day: 12)+ end+ expect_bill(mortgage, due_on: current_month.change(day: 25))+ spend(current_month, 200, day: 5)++ insights = generate++ assert_equal 1, insights.size+ assert_equal "above", insights.first.metadata[:direction]+ pace = BigDecimal(current_month.end_of_month.day) / 10+ assert_equal Money.new(700 + 200 * pace, "USD").format, insights.first.facts[:projected_spend]+ end+ end++ # Bills do not hide the rest of the category: spending outside them that is+ # running ahead of its usual pace is still reported.+ test "flags unplanned spending running ahead in a category with bills" do+ rent = create_bill(category: @category, amount: 1_000, name: "Rent", day: 3)++ travel_to anchor do+ baseline_months.each do |month|+ pay_bill(rent, date: month.change(day: 3))+ spend(month, 300, day: 12)+ end+ pay_bill(rent, date: current_month.change(day: 3))+ spend(current_month, 600, day: 5)++ insights = generate++ assert_equal 1, insights.size+ assert_equal "above", insights.first.metadata[:direction]+ end+ end++ # An annual premium paid this month makes the month dearer than the last+ # three, but it was planned: the spending outside bills is as usual, so+ # there is no trend to report.+ test "does not flag a month made dearer only by a bill" do+ @anchor_day = 15+ rent = create_bill(category: @category, amount: 1_000, name: "Rent", day: 3)+ premium = create_bill(category: @category, amount: 800, name: "Home insurance", day: 10)++ travel_to anchor do+ baseline_months.each do |month|+ pay_bill(rent, date: month.change(day: 3))+ spend(month, 100, day: 12)+ end+ pay_bill(rent, date: current_month.change(day: 3))+ pay_bill(premium, date: current_month.change(day: 10))+ spend(current_month, 50, day: 5)++ assert_empty generate+ end+ end++ # The mirror case: the same premium paid in one of the baseline months lifts+ # the average, and a normal month must not read as spending falling.+ test "does not flag a month made cheaper only by a bill in the baseline" do+ @anchor_day = 15+ rent = create_bill(category: @category, amount: 1_000, name: "Rent", day: 3)+ premium = create_bill(category: @category, amount: 2_400, name: "Home insurance", day: 10)++ travel_to anchor do+ baseline_months.each do |month|+ pay_bill(rent, date: month.change(day: 3))+ spend(month, 100, day: 12)+ end+ pay_bill(premium, date: month_start(2).change(day: 10))+ pay_bill(rent, date: current_month.change(day: 3))+ spend(current_month, 50, day: 5)++ assert_empty generate+ end+ end++ # Money saved up in a rollover envelope is there to be spent in a lump: a+ # holiday paid from it is the plan, not a trend.+ test "does not flag a rollover category spending within its envelope" do+ @anchor_day = 15+ budget_line(rollover_enabled: true, budgeted_spending: 100, rolled_over_amount: 900)++ travel_to anchor do+ baseline_months.each { |month| spend(month, 100) }+ spend(current_month, 600, day: 5)++ assert_empty generate+ end+ end++ # The feed is the whole family's, so only the household budget may hold+ # back an anomaly: one member's personal envelope says nothing about what+ # the others spent.+ test "ignores a personal budget's rollover envelope" do+ @anchor_day = 15+ budget_line(user: users(:family_admin), rollover_enabled: true, budgeted_spending: 100, rolled_over_amount: 900)++ travel_to anchor do+ baseline_months.each { |month| spend(month, 100) }+ spend(current_month, 600, day: 5)++ assert_equal [ "above" ], generate.map { |insight| insight.metadata[:direction] }+ end+ end++ # The carry often sits on a ring-fenced subcategory (Insurance under Home)+ # while the parent has none. Spending from that envelope is still planned.+ test "does not flag spending from a subcategory's rollover envelope" do+ @anchor_day = 15+ insurance = @family.categories.create!(name: "Pace Test Insurance", parent: @category)+ budget_line(budgeted_spending: 200)+ budget_line(category: insurance, rollover_enabled: true, budgeted_spending: 100, rolled_over_amount: 900)++ travel_to anchor do+ baseline_months.each { |month| spend(month, 100) }+ create_transaction(category: insurance, amount: 600, date: current_month.change(day: 5), name: "Insurance premium")++ assert_empty generate+ end+ end++ # A bill paid from a rollover envelope is already planned as a bill. Counted+ # again as envelope spend, the 400 premium would hide the 600 spent+ # elsewhere in the category.+ test "counts a bill paid from a rollover envelope once" do+ @anchor_day = 15+ insurance = @family.categories.create!(name: "Pace Test Insurance", parent: @category)+ premium = create_bill(category: insurance, amount: 400, name: "Insurance", day: 3)+ budget_line(budgeted_spending: 200)+ budget_line(category: insurance, rollover_enabled: true, budgeted_spending: 100, rolled_over_amount: 900)++ travel_to anchor do+ baseline_months.each do |month|+ pay_bill(premium, date: month.change(day: 3))+ spend(month, 300, day: 12)+ end+ pay_bill(premium, date: current_month.change(day: 3))+ spend(current_month, 600, day: 5)++ assert_equal [ "above" ], generate.map { |insight| insight.metadata[:direction] }+ end+ end++ # A cushion builds up when the allocation runs above what the category+ # spends. Spending that keeps within the month's own allocation draws+ # nothing from it, so a real rise against the baseline still shows, however+ # much has been carried over.+ test "flags a rise within the month's allocation of a rollover envelope" do+ @anchor_day = 15+ budget_line(rollover_enabled: true, budgeted_spending: 400, rolled_over_amount: 1_200)++ travel_to anchor do+ baseline_months.each { |month| spend(month, 100) }+ spend(current_month, 150, day: 5)++ assert_equal [ "above" ], generate.map { |insight| insight.metadata[:direction] }+ end+ end++ # The parent's envelope holds only what its ring-fenced subcategories don't:+ # their spending is drawn from their own envelope and not again from the+ # parent's, which would leave none of the parent's own rise unplanned.+ test "draws a ring-fenced subcategory's spending from its own envelope only" do+ @anchor_day = 15+ insurance = @family.categories.create!(name: "Pace Test Insurance", parent: @category)+ budget_line(rollover_enabled: true, budgeted_spending: 200, rolled_over_amount: 1_000)+ budget_line(category: insurance, rollover_enabled: true, budgeted_spending: 100, rolled_over_amount: 600)++ travel_to anchor do+ baseline_months.each { |month| spend(month, 100) }+ create_transaction(category: insurance, amount: 600, date: current_month.change(day: 5), name: "Insurance premium")+ spend(current_month, 300, day: 6)++ assert_equal [ "above" ], generate.map { |insight| insight.metadata[:direction] }+ end+ end++ # The category's spending is gross of refunds, so what an envelope drew+ # has to be too. Read net, the 400 refund would leave 400 of spending the+ # envelope paid for looking unplanned.+ test "measures an envelope's draw gross of refunds, like the category's spending" do+ @anchor_day = 15+ insurance = @family.categories.create!(name: "Pace Test Insurance", parent: @category)+ premium = create_bill(category: insurance, amount: 400, name: "Insurance", day: 3)+ budget_line(budgeted_spending: 200)+ budget_line(category: insurance, rollover_enabled: true, budgeted_spending: 100, rolled_over_amount: 900)++ travel_to anchor do+ baseline_months.each do |month|+ pay_bill(premium, date: month.change(day: 3))+ spend(month, 300, day: 12)+ end+ pay_bill(premium, date: current_month.change(day: 3))+ create_transaction(category: insurance, amount: 600, date: current_month.change(day: 5), name: "Insurance excess")+ create_transaction(category: insurance, amount: -400, date: current_month.change(day: 6), name: "Insurance refund")++ assert_empty generate+ end+ end++ test "flags a rollover category that has outspent its envelope" do+ @anchor_day = 15+ budget_line(rollover_enabled: true, budgeted_spending: 100, rolled_over_amount: 400)++ travel_to anchor do+ baseline_months.each { |month| spend(month, 100) }+ spend(current_month, 600, day: 5)++ assert_equal [ "above" ], generate.map { |insight| insight.metadata[:direction] }+ end+ end++ test "flags a category without rollover even when its budget covers the spend" do+ @anchor_day = 15+ budget_line(rollover_enabled: false, budgeted_spending: 1_000)++ travel_to anchor do+ baseline_months.each { |month| spend(month, 100) }+ spend(current_month, 600, day: 5)++ assert_equal [ "above" ], generate.map { |insight| insight.metadata[:direction] }+ end+ end++ # The generator runs nightly for every family, so bills are read in bulk:+ # more of them must not mean more queries.+ test "reads bills with a fixed number of queries" do+ categories = [ @category ] + 2.times.map do |i|+ @family.categories.create!(name: "Pace Test Cat #{i}", color: "#101010", lucide_icon: "circle")+ end++ travel_to anchor do+ bills = categories.map { |category| create_bill(category: category, amount: 100, name: category.name, day: 3) }+ [ *baseline_months, current_month ].each { |month| pay_bill(bills.first, date: month.change(day: 3)) }+ expect_bill(bills.first, due_on: current_month.change(day: 25))+ generate # loads the account-type ids IncomeStatement keeps per process+ with_one_bill = uncached_query_count { generate }++ bills.drop(1).each do |bill|+ [ *baseline_months, current_month ].each { |month| pay_bill(bill, date: month.change(day: 3)) }+ expect_bill(bill, due_on: current_month.change(day: 25))+ end++ assert_equal with_one_bill, uncached_query_count { generate }+ end+ end++ private+ # IncomeStatement caches its totals, so each count starts cold.+ def uncached_query_count(&block)+ Rails.cache.clear+ ActiveRecord::Base.uncached { capture_sql_queries(&block).size }+ end++ def split_mortgage_bill+ @mortgage_category = @family.categories.create!(name: "Pace Test Mortgage", parent: @category)+ create_bill(category: @mortgage_category, amount: 1_500, name: "Mortgage", day: 3)+ end++ def pay_split_instalment(mortgage, month)+ split_payment(pay_bill(mortgage, date: month.change(day: 3)),+ { amount: 700, category: @mortgage_category }, { amount: 800, kind: "funds_movement" })+ end++ def budget_line(category: @category, user: nil, **attributes)+ budget = @family.budgets.find_or_create_by!(start_date: current_month, end_date: current_month.end_of_month, user: user) do |b|+ b.budgeted_spending = 2_000+ b.expected_income = 3_000+ b.currency = "USD"+ end+ budget.budget_categories.create!(category: category, currency: "USD", **attributes)+ endenddiff --git a/test/models/recurring_occurrence_test.rb b/test/models/recurring_occurrence_test.rbindex 1a817f6590..d3d9de7a50 100644--- a/test/models/recurring_occurrence_test.rb+++ b/test/models/recurring_occurrence_test.rb@@ -1,6 +1,8 @@require "test_helper"class RecurringOccurrenceTest < ActiveSupport::TestCase+ include EntriesTestHelper+def setup@family = families(:dylan_family)@series = recurring_transactions(:netflix_subscription)@@ -21,6 +23,44 @@ class RecurringOccurrenceTest < ActiveSupport::TestCaseassert_equal 18.99, occurrence.resolved_expected_amountend+ test "remaining_spending_money is the whole remaining amount for a series never split" do+ occurrence = create_occurrence++ assert_equal occurrence.remaining_amount_money, occurrence.remaining_spending_money+ end++ # Only the interest of a mortgage instalment is spending; the principal is a+ # transfer to the loan, and an excluded part is not counted either.+ test "remaining_spending_money keeps the spending share of the series' latest split charge" do+ interest = @family.categories.create!(name: "Mortgage interest")+ mortgage = create_bill(category: interest, amount: 1_500, name: "Mortgage")+ split_payment(pay_bill(mortgage, date: Date.current - 1.month),+ { amount: 700, category: interest },+ { amount: 40, category: interest, excluded: true },+ { amount: 760, kind: "funds_movement" })++ assert_equal Money.new(700, "USD"), expect_bill(mortgage, due_on: Date.current).remaining_spending_money+ end++ # A charge split into spending and a contribution to an investment account+ # reserves the contribution only for a family that counts investing as+ # spending, as IncomeStatement::Totals does.+ test "remaining_spending_money counts a split contribution only when investing counts as spending" do+ [ [ true, 1_000 ], [ false, 200 ] ].each do |as_spending, expected|+ @family.update!(investment_contributions_as_spending: as_spending)+ groceries = @family.categories.create!(name: "Groceries #{as_spending}")+ bill = create_bill(category: groceries, amount: 1_000, name: "Groceries and savings #{as_spending}")+ split_payment(pay_bill(bill, date: Date.current - 1.month),+ { amount: 200, category: groceries },+ { amount: 800, kind: "investment_contribution" })+ due = expect_bill(bill, due_on: Date.current)++ assert_equal Money.new(expected, "USD"), due.remaining_spending_money, "as_spending: #{as_spending}"+ loaded = RecurringOccurrence.open_bills_due(@family, Date.current..Date.current).find { |o| o.id == due.id }+ assert_equal Money.new(expected, "USD"), loaded.remaining_spending_money, "open_bills_due, as_spending: #{as_spending}"+ end+ end+test "average strategy resolves through the series variance" do@series.update!(amount_strategy: "average", expected_amount_min: 10, expected_amount_max: 20, expected_amount_avg: 15.5)occurrence = create_occurrencediff --git a/test/support/entries_test_helper.rb b/test/support/entries_test_helper.rbindex 326a754812..a919d60048 100644--- a/test/support/entries_test_helper.rb+++ b/test/support/entries_test_helper.rb@@ -108,4 +108,48 @@ module EntriesTestHelpertransferend++ # A manual bill in `category` with no occurrences: creating a series+ # generates its own, which tests clear so they assert against exactly the+ # ones they add with pay_bill and expect_bill.+ def create_bill(category:, amount:, name: "Bill", day: 1, account: accounts(:depository))+ bill = category.family.recurring_transactions.create!(+ name: name, account: account, amount: amount, currency: "USD", bill_type: "bill",+ category_id: category.id, expected_day_of_month: day, anchor_date: Date.current,+ last_occurrence_date: Date.current, next_expected_date: Date.current,+ status: "active", manual: true+ )+ bill.recurring_occurrences.destroy_all+ bill+ end++ # The entry that pays `bill` on `date`, and the paid occurrence it settles.+ # The entry takes the bill's category unless `category:` says otherwise.+ def pay_bill(bill, date:, amount: bill.amount, category: bill.category)+ entry = create_transaction(category: category, account: bill.account, amount: amount, date: date, name: "#{bill.name} #{date}")+ occurrence = bill.recurring_occurrences.create!(+ family: bill.family, original_due_on: date, due_on: date, currency: bill.currency,+ expected_amount: amount, status: "paid", closed_at: Time.current, closed_source: "auto"+ )+ occurrence.allocations.create!(entry: entry, allocated_amount: amount, currency: bill.currency, source: "auto_matched")+ entry+ end++ # Splits a payment into `parts` ({ amount:, category:, kind:, excluded: }), the way a+ # family splits a mortgage instalment into its interest and a transfer of+ # the principal to the loan. A part with a transfer kind is that transfer.+ def split_payment(entry, *parts)+ children = entry.split!(parts.map.with_index(1) do |part, i|+ { name: "#{entry.name} part #{i}", amount: part[:amount], category_id: part[:category]&.id, excluded: part[:excluded] }+ end)+ children.zip(parts) { |child, part| child.entryable.update!(kind: part[:kind]) if part[:kind] }+ children+ end++ # An occurrence of `bill` still waiting to be paid.+ def expect_bill(bill, due_on:, amount: bill.amount)+ bill.recurring_occurrences.create!(+ family: bill.family, original_due_on: due_on, due_on: due_on, currency: bill.currency, expected_amount: amount+ )+ endend