Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add an insight for fixed commitments as a share of income (#5193)

David Gil15d87e18b2c6
diff --git a/app/controllers/bills_controller.rb b/app/controllers/bills_controller.rb
index fb0aa26ebe..3a2af43c5c 100644
--- a/app/controllers/bills_controller.rb
+++ b/app/controllers/bills_controller.rb
@@ -475,15 +475,9 @@ class BillsController < ApplicationController
# payments alike). Inactive series ride along so their leftover open
# occurrences can render as Dormant instead of haunting Past Due.
def payable_series_ids
- debt_accounts = Account.where(accountable_type: %w[CreditCard Loan]).select(:id)
-
Current.family.recurring_transactions
.where(status: %w[active inactive])
- .where("amount > 0")
- .merge(
- RecurringTransaction.where(destination_account_id: nil)
- .or(RecurringTransaction.where(destination_account_id: debt_accounts))
- )
+ .obligations(%w[CreditCard Loan])
.accessible_by(Current.user)
.select(:id)
end
diff --git a/app/helpers/insights_helper.rb b/app/helpers/insights_helper.rb
index 49c5ba9f8e..e6d762fec0 100644
--- a/app/helpers/insights_helper.rb
+++ b/app/helpers/insights_helper.rb
@@ -13,7 +13,8 @@ module InsightsHelper
"maintained_goal_depleted" => "shield-alert",
"bill_not_covered" => "calendar-x",
"loan_payment_change" => "landmark",
- "bank_fees" => "receipt"
+ "bank_fees" => "receipt",
+ "fixed_commitments_ratio" => "scale"
}.freeze
def insight_icon_key(insight)
@@ -90,6 +91,8 @@ module InsightsHelper
facts["new_payment"] && [ facts["new_payment"], facts["effective_on"] ]
when "bank_fees"
facts["amount"] && [ facts["amount"], t("insights.figures.fee_charges", count: facts["count"].to_i) ]
+ when "fixed_commitments_ratio"
+ facts["current_ratio"] && [ "#{facts["current_ratio"]}%", t("insights.figures.of_income") ]
end
end
@@ -119,8 +122,8 @@ module InsightsHelper
start_date: insight.period_start.to_s, end_date: insight.period_end.to_s }) }
when "subscription_audit"
{ text: t("insights.actions.subscription_audit"), href: recurring_transactions_path }
- when "cash_flow_warning"
- { text: t("insights.actions.cash_flow_warning"), href: recurring_transactions_path }
+ when "cash_flow_warning", "fixed_commitments_ratio"
+ { text: t("insights.actions.#{insight.insight_type}"), href: recurring_transactions_path }
when "savings_rate_change"
return nil unless insight.period_start && insight.period_end
{ text: t("insights.actions.savings_rate_change"),
@@ -202,7 +205,7 @@ module InsightsHelper
:negative
when "loan_payment_change"
metadata["new_payment"].to_f < metadata["previous_payment"].to_f ? :positive : :warning
- when "budget_at_risk", "maintained_goal_depleted", "bank_fees"
+ when "budget_at_risk", "maintained_goal_depleted", "bank_fees", "fixed_commitments_ratio"
# Warning, not negative: the reserve is short, not overdrawn, and red is
# reserved here for money actually going the wrong side of zero.
:warning
diff --git a/app/models/insight.rb b/app/models/insight.rb
index 0d6dc607bb..c33dfd0645 100644
--- a/app/models/insight.rb
+++ b/app/models/insight.rb
@@ -30,6 +30,7 @@ class Insight < ApplicationRecord
bill_not_covered
loan_payment_change
bank_fees
+ fixed_commitments_ratio
].freeze
# How many the dashboard widget shows. Shared so PagesController (first render)
diff --git a/app/models/insight/generator_registry.rb b/app/models/insight/generator_registry.rb
index 6582fa953a..2e4c48052c 100644
--- a/app/models/insight/generator_registry.rb
+++ b/app/models/insight/generator_registry.rb
@@ -15,7 +15,8 @@ class Insight::GeneratorRegistry
Insight::Generators::MaintainedGoalDepletedGenerator,
Insight::Generators::BillNotCoveredGenerator,
Insight::Generators::LoanRepaymentChangeGenerator,
- Insight::Generators::BankFeesGenerator
+ Insight::Generators::BankFeesGenerator,
+ Insight::Generators::FixedCommitmentsRatioGenerator
].freeze
Result = Data.define(:insights, :succeeded_types)
diff --git a/app/models/insight/generators/fixed_commitments_ratio_generator.rb b/app/models/insight/generators/fixed_commitments_ratio_generator.rb
new file mode 100644
index 0000000000..8b5a322216
--- /dev/null
+++ b/app/models/insight/generators/fixed_commitments_ratio_generator.rb
@@ -0,0 +1,224 @@
+# Tracks how much of a typical month's income is already spoken for by
+# recurring commitments, and speaks up when that share rises RISE_THRESHOLD_PP
+# points against six months ago, or crosses CEILING_PCT.
+#
+# ratio = monthly equivalent of the recurring outflows in force
+# / median monthly income over the six complete months before
+#
+# The median, not the mean, so a month with extra pay (a bonus, a thirteenth
+# payment) does not make commitments look smaller than they are.
+#
+# Outflows are expense series plus recurring payments into a loan. Payments
+# into a credit card are left out: they repay spending that is already counted
+# on the card, much of it not fixed at all. Both sides of the ratio read only
+# accounts every active member can see, since the feed is shared and the body
+# names series and income.
+#
+# The figure six months ago is rebuilt from the series in force on that date,
+# priced through their price history, so a series swapped for another of the
+# same cost is not a rise. Cadence changes are not tracked: every series is
+# normalised at its current cadence.
+class Insight::Generators::FixedCommitmentsRatioGenerator < Insight::Generator
+ produces "fixed_commitments_ratio"
+
+ RISE_THRESHOLD_PP = 5
+ CEILING_PCT = 50
+ WINDOW_MONTHS = 6
+ MAX_CONTRIBUTORS = 3
+ DEDUP_KEY = "fixed_commitments_ratio"
+ # A nightly run plus slack for a late one.
+ LIVE_WITHIN = 36.hours
+
+ def generate
+ return [] if family.recurring_transactions_disabled?
+
+ current_income = median_monthly_income(months_back: 0)
+ previous_income = median_monthly_income(months_back: WINDOW_MONTHS)
+ return [] unless current_income.positive? && previous_income.positive?
+
+ current = monthly_commitments(series.select(&:active?))
+ previous = monthly_commitments(series.select { |recurring| in_force_on_reference_date?(recurring) }, on: reference_date)
+ return [] if current.empty? || previous.empty?
+
+ current_total = current.values.sum
+ previous_total = previous.values.sum
+ current_ratio = current_total / current_income * 100
+ previous_ratio = previous_total / previous_income * 100
+ rise_pp = current_ratio - previous_ratio
+ crossed_ceiling = previous_ratio < CEILING_PCT && current_ratio >= CEILING_PCT
+ return [] unless rise_pp >= RISE_THRESHOLD_PP || crossed_ceiling
+
+ # The share of the rise that comes from income alone: the same commitments
+ # measured against the new income instead of the old.
+ income_part_pp = current_total / current_income * 100 - current_total / previous_income * 100
+ variant = current_ratio >= CEILING_PCT ? "over_half" : "up"
+
+ [
+ build_insight(
+ insight_type: "fixed_commitments_ratio",
+ priority: variant == "over_half" ? "high" : "medium",
+ title: I18n.t("insights.titles.fixed_commitments_ratio.#{variant}"),
+ template_key: "fixed_commitments_ratio",
+ facts: {
+ current_ratio: decimal_fact(current_ratio),
+ previous_ratio: decimal_fact(previous_ratio),
+ commitments: format_money(current_total),
+ income: format_money(current_income),
+ explanation: explanation(current, previous, previous_income: previous_income, current_income: current_income,
+ mention_income: income_part_pp >= rise_pp / 2)
+ },
+ # Banded by the rise threshold: the reference window rolls every month
+ # and averaged amounts nudge with every charge, so only a climb into the
+ # next band is a new insight. One key for the family, so an acknowledged
+ # rise is not raised again next month with the same numbers. The day the
+ # rise was first seen tells a rise that came back apart from one that
+ # never left, even in the same band.
+ metadata: {
+ current_band: peak_band((current_ratio / RISE_THRESHOLD_PP).floor * RISE_THRESHOLD_PP),
+ rise_since: live_metadata.fetch("rise_since", Date.current.iso8601),
+ accounts_digest: shared_accounts_digest
+ },
+ period: income_window(months_back: 0),
+ dedup_key: DEDUP_KEY
+ )
+ ]
+ end
+
+ private
+ # The last day of the earlier income window, so the comparison moves once
+ # a month with the windows rather than every night.
+ def reference_date
+ @reference_date ||= income_window(months_back: WINDOW_MONTHS).end_date
+ end
+
+ # Every outflow series that was ever confirmed. Suggestions were never in
+ # force. Both endpoints must be shared, not just the paying account: a
+ # payment into a loan only one member can see stays out too.
+ def series
+ @series ||= family.recurring_transactions
+ .where.not(status: :suggested)
+ .obligations(%w[Loan])
+ .within_accounts(shared_accounts.visible)
+ .includes(:merchant, :recurrence_rules, :recurring_price_changes)
+ .to_a
+ end
+
+ # A series that is no longer active counts until it was cancelled or, as
+ # a pause records no date, through the cycle its last payment covered. One
+ # that never produced an occurrence was a suggestion dismissed straight to
+ # ended, never a commitment.
+ def in_force_on_reference_date?(recurring)
+ return false if started_after_reference_date?(recurring)
+ return true if recurring.active?
+ return false unless first_due_on.key?(recurring.id)
+
+ ended_on = recurring.cancelled_on || recurring.last_occurrence_date + cycle_days(recurring)
+ ended_on >= reference_date
+ end
+
+ # The band a live insight last showed, so a ratio easing into a lower band
+ # does not read as a change and reopen an acknowledged warning.
+ def peak_band(band)
+ [ band, live_metadata["current_band"].to_i ].max
+ end
+
+ # Metadata of the insight while its rise is still live; empty once it has
+ # cleared, so band and start begin again. The job expires only unread and
+ # read rows, so for an acknowledged one "still live" means the job
+ # regenerated it on its last nightly run; a missed run errs towards
+ # showing the warning again.
+ def live_metadata
+ @live_metadata ||= family.insights.where.not(status: :expired)
+ .where(generated_at: LIVE_WITHIN.ago..)
+ .find_by(dedup_key: DEDUP_KEY)&.metadata || {}
+ end
+
+ # Only a start Sure actually saw counts as new. A series known before the
+ # reference date was in force then. One confirmed since is traced back
+ # through its earliest occurrence or a past first due date, but history is
+ # backfilled for a limited window only, so a start within one cycle of
+ # where that window could begin is the edge of the history, not the start
+ # of the commitment. A series declared going forward, with nothing before
+ # its creation, is assumed to have been there all along.
+ def started_after_reference_date?(recurring)
+ created_on = recurring.created_at.to_date
+ return false if created_on <= reference_date
+
+ first_seen = [ first_due_on[recurring.id], recurring.anchor_date ].compact.min
+ return false if first_seen.nil? || first_seen >= created_on
+
+ history_floor = [ reference_date, created_on << RecurringTransaction::Pipeline::FIRST_RUN_BACKFILL_MONTHS ].max
+ first_seen > history_floor + cycle_days(recurring)
+ end
+
+ def cycle_days(recurring)
+ (365.25 / recurring.schedule.occurrences_per_year).round
+ end
+
+ def first_due_on
+ @first_due_on ||= family.recurring_occurrences
+ .where(recurring_transaction_id: series.map(&:id))
+ .group(:recurring_transaction_id)
+ .minimum(:due_on)
+ end
+
+ # { series => monthly amount in the family currency }. A series with no
+ # exchange rate is left out, as on the Bills page.
+ def monthly_commitments(series_list, on: nil)
+ series_list.each_with_object({}) do |recurring, amounts|
+ amounts[recurring] = recurring.monthly_equivalent_amount(on: on).exchange_to(family.currency).amount
+ rescue Money::ConversionError
+ next
+ end
+ end
+
+ # The complete months ending `months_back` months before last month. The
+ # end is the day before the next month starts: shifting 30 April back six
+ # months would land on 30 October and drop the 31st.
+ def income_window(months_back:)
+ last_month_start = Period.last_month_for(family).start_date << months_back
+ Period.custom(start_date: last_month_start << (WINDOW_MONTHS - 1), end_date: (last_month_start >> 1) - 1)
+ end
+
+ def median_monthly_income(months_back:)
+ window_start = income_window(months_back: months_back).start_date
+ totals = (0...WINDOW_MONTHS).map do |offset|
+ start_date = window_start >> offset
+ period = Period.custom(start_date: start_date, end_date: (start_date >> 1) - 1)
+ income_statement.income_totals(period: period).total.to_d
+ end
+ median(totals)
+ end
+
+ def median(values)
+ sorted = values.sort
+ middle = sorted.size / 2
+ sorted.size.odd? ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2
+ end
+
+ # The series that grew the most (new ones count in full), and the drop in
+ # income when it drove at least half the rise. A series that replaced
+ # another is compared with the one it replaced.
+ def explanation(current, previous, previous_income:, current_income:, mention_income:)
+ predecessors = previous.keys.select(&:replaced_by_id).index_by(&:replaced_by_id)
+ contributors = current.filter_map do |recurring, amount|
+ before = previous[recurring] || previous[predecessors[recurring.id]]
+ added = amount - (before || 0)
+ [ recurring, added, before ] if added.positive?
+ end
+
+ sentences = []
+ if contributors.any?
+ names = contributors.max_by(MAX_CONTRIBUTORS) { |_, added, _| added }.map do |recurring, added, before|
+ I18n.t("insights.fixed_commitments_ratio.contributor.#{before ? "raised" : "new"}",
+ name: recurring.display_name, amount: format_money(added))
+ end
+ sentences << I18n.t("insights.fixed_commitments_ratio.contributors", list: names.to_sentence)
+ end
+ if mention_income
+ sentences << I18n.t("insights.fixed_commitments_ratio.income_fell",
+ previous_income: format_money(previous_income), current_income: format_money(current_income))
+ end
+ sentences.join(" ")
+ end
+end
diff --git a/app/models/recurring_transaction.rb b/app/models/recurring_transaction.rb
index f4c713ea4b..d6cc556409 100644
--- a/app/models/recurring_transaction.rb
+++ b/app/models/recurring_transaction.rb
@@ -82,6 +82,7 @@ class RecurringTransaction < ApplicationRecord
after_commit :regenerate_future_occurrences, on: :update, if: :schedule_shape_changed?
before_save :preserve_detected_name, if: -> { name_changed? && name_was.present? && matcher_hints.to_h["detected_name"].blank? }
after_commit :pin_amount_on_dates_already_due, on: :update, if: :saved_change_to_amount?
+ after_update :record_price_change, if: :saved_change_to_amount?
# Form state for the frequency picker and the create-bill dialog;
# FrequencyPreset and the controller translate these on save. Not persisted.
@@ -281,6 +282,32 @@ class RecurringTransaction < ApplicationRecord
end
end
+ # An edited amount is a price change from today, kept in the price history
+ # so anything reading an earlier date (see #amount_on) still sees the old
+ # price. Skipped when the history already reached the new amount: the
+ # PriceChangeDetector records its change before updating the series, and a
+ # manual series edited to a detected price is that same change. A second
+ # edit the same day moves that day's change rather than adding one; over a
+ # detected change it becomes the user's, as the charge no longer backs it.
+ # A suggestion was never a commitment, and a new currency or a change of
+ # sign (bill to income) is not a new price.
+ def record_price_change
+ was, now = saved_change_to_amount
+ return if suggested? || status_before_last_save == "suggested" || saved_change_to_currency?
+ return unless was.positive? && now.positive?
+ return if recurring_price_changes.order(:effective_on).last&.new_amount == now
+
+ today = recurring_price_changes.find_by(effective_on: Date.current)
+ if today.nil?
+ recurring_price_changes.create!(effective_on: Date.current, previous_amount: was, new_amount: now,
+ currency: currency, source: "user")
+ elsif today.previous_amount == now
+ today.destroy!
+ else
+ today.update!(new_amount: now, source: "user", entry: nil)
+ end
+ end
+
# A destination account is the definition of a transfer, so the type derives
# from the shape rather than every creation path remembering to set it.
def derive_transfer_bill_type
@@ -366,16 +393,20 @@ class RecurringTransaction < ApplicationRecord
# credit-card or loan payment is a real obligation with a real due date,
# even though it is a transfer and not spending. (It stays excluded from
# any budget/category math for exactly that reason.)
- scope :payable, -> {
+ scope :payable, -> { active.obligations(%w[CreditCard Loan]) }
+
+ # Outflows owed to someone, whatever the series' status: expense series and
+ # recurring transfers into accounts of the given `debt_types`.
+ scope :obligations, ->(debt_types) {
# Correlated to the row rather than a free-standing id list: the bare
# subquery scanned every account in the installation on every call, and
# the destination must belong to the series' own family.
- debt_destination = Account.where(accountable_type: %w[CreditCard Loan])
+ debt_destination = Account.where(accountable_type: debt_types)
.where("accounts.id = recurring_transactions.destination_account_id")
.where("accounts.family_id = recurring_transactions.family_id")
- active.where("amount > 0")
- .merge(where(destination_account_id: nil).or(where(debt_destination.arel.exists)))
+ where("recurring_transactions.amount > 0")
+ .merge(where(destination_account_id: nil).or(where(debt_destination.arel.exists)))
}
# The bills that want an action from you. Autopay bills still belong on the
@@ -441,16 +472,28 @@ class RecurringTransaction < ApplicationRecord
# a $120 annual bill contributes $10, a $10 weekly bill about $43.45. This
# is the honest number for "recurring commitment" style totals; summing raw
# amounts across mixed cadences answers no meaningful question.
+ #
# A one-off is a single payment, not a rate, so it adds nothing to
# "per month" commitment totals. The occurrence still shows on its date.
+ #
+ # `on:` prices it as it stood on that date instead of today; see #amount_on.
def one_off?
RecurringTransaction::FrequencyPreset.detect(self).key == RecurringTransaction::FrequencyPreset::ONCE
end
- def monthly_equivalent_amount
- return amount_money * 0 if one_off?
+ def monthly_equivalent_amount(on: nil)
+ price = on ? Money.new(amount_on(on), currency) : amount_money
+ return price * 0 if one_off?
+
+ price * (schedule.occurrences_per_year / 12.0)
+ end
- amount_money * (schedule.occurrences_per_year / 12.0)
+ # What this series charged on `date`, read back through its price history:
+ # the previous amount of the first change after that date, or today's amount
+ # when nothing has changed since. Preload-aware like #recent_price_changes.
+ def amount_on(date)
+ later = recurring_price_changes.select { |change| change.effective_on > date }.min_by(&:effective_on)
+ later ? later.previous_amount : amount
end
# The newest price changes, most recent first. Sorts in Ruby when a caller
@@ -481,25 +524,28 @@ class RecurringTransaction < ApplicationRecord
cycle_days = 365.25 / schedule.occurrences_per_year
((Date.current - next_due_date).to_i / cycle_days).floor
end
- scope :accessible_by, ->(user) {
- accessible_account_ids = Account.accessible_by(user).select(:id)
- # A recurring row is accessible when:
- # * its account_id is in the user's accessible set or null (legacy rows
- # with no account scoping survive), AND
- # * its destination_account_id is also accessible OR null (so a recurring
- # transfer never leaks into the list of a user without access to BOTH
- # endpoints).
+ scope :accessible_by, ->(user) { within_accounts(Account.accessible_by(user)) }
+
+ # Series whose endpoints all fall inside `accounts`, an Account relation: the
+ # accounts one user can access, or the ones every member of a family can.
+ scope :within_accounts, ->(accounts) {
+ # A recurring row is kept when:
+ # * its account_id is in `accounts` or null (legacy rows with no account
+ # scoping survive), AND
+ # * its destination_account_id is also in `accounts` OR null (so a
+ # recurring transfer never leaks into the list of a user without
+ # access to BOTH endpoints).
#
# Written as one raw SQL predicate on purpose. ActiveRecord's
# `merge` replaces an existing hash predicate on the same column instead of
# AND-ing it, so a hash-style `where(destination_account_id: ...)` here would
# silently wipe out a caller's own destination filter when composed through
# `.merge(RecurringTransaction.accessible_by(user))`.
- # Both endpoints (ignoring NULLs) must be inside the accessible set, so the
+ # Both endpoints (ignoring NULLs) must be inside the set, so the
# set is evaluated once instead of once per column.
where(
"array_remove(ARRAY[recurring_transactions.account_id, recurring_transactions.destination_account_id], NULL) <@ ARRAY(?)",
- accessible_account_ids
+ accounts.select(:id)
)
}
diff --git a/config/locales/views/insights/en.yml b/config/locales/views/insights/en.yml
index cf5ad8dc1d..fab4e5bebb 100644
--- a/config/locales/views/insights/en.yml
+++ b/config/locales/views/insights/en.yml
@@ -49,6 +49,7 @@ en:
bill_not_covered: Bills
loan_payment_change: Loan payment
bank_fees: Fees
+ fixed_commitments_ratio: Fixed commitments
meta:
next_n_days:
one: Next day
@@ -63,6 +64,7 @@ en:
on_pace: on pace
of_budget: of budget
need_attention: need attention
+ of_income: of income
days_overdue:
one: "%{count} day overdue"
other: "%{count} days overdue"
@@ -85,6 +87,7 @@ en:
bill_not_covered: Go to account
loan_payment_change: View loan
bank_fees: View fees
+ fixed_commitments_ratio: Review recurring transactions
titles:
spending_anomaly:
above: "%{category} spending is trending up"
@@ -108,6 +111,9 @@ en:
up: "%{account} payment is going up"
down: "%{account} payment is going down"
bank_fees: Fees on %{account}
+ fixed_commitments_ratio:
+ up: Fixed commitments are taking more of your income
+ over_half: Fixed commitments now take half your income or more
templates:
spending_anomaly:
above: You're on pace to spend %{projected_spend} on %{category} this month, about %{deviation_pct}% more than your recent monthly average of %{baseline_spend}.
@@ -134,3 +140,10 @@ en:
bank_fees:
recurring: "%{account} had %{amount} in fees over the last %{days} days."
new: "%{account} had %{amount} in fees over the last %{days} days, after none in the %{days} days before."
+ fixed_commitments_ratio: "Recurring commitments of %{commitments} a month take %{current_ratio}% of your typical monthly income of %{income}, up from %{previous_ratio}% six months ago. %{explanation}"
+ fixed_commitments_ratio:
+ contributors: "Main changes: %{list}."
+ contributor:
+ new: "%{name} (new, %{amount} a month)"
+ raised: "%{name} (%{amount} a month more)"
+ income_fell: Your typical monthly income fell from %{previous_income} to %{current_income}.
diff --git a/config/locales/views/insights/es.yml b/config/locales/views/insights/es.yml
index b2eb2e1444..2056bb4a95 100644
--- a/config/locales/views/insights/es.yml
+++ b/config/locales/views/insights/es.yml
@@ -49,6 +49,7 @@ es:
bill_not_covered: Recibos
loan_payment_change: Cuota del préstamo
bank_fees: Comisiones
+ fixed_commitments_ratio: Compromisos fijos
meta:
next_n_days:
one: Próximo día
@@ -63,6 +64,7 @@ es:
on_pace: al ritmo previsto
of_budget: del presupuesto
need_attention: requieren atención
+ of_income: de tus ingresos
days_overdue:
one: "%{count} día de retraso"
other: "%{count} días de retraso"
@@ -85,6 +87,7 @@ es:
bill_not_covered: Ir a la cuenta
loan_payment_change: Ver préstamo
bank_fees: Ver comisiones
+ fixed_commitments_ratio: Revisar transacciones recurrentes
titles:
spending_anomaly:
above: El gasto en %{category} va en aumento
@@ -108,6 +111,9 @@ es:
up: La cuota de %{account} va a subir
down: La cuota de %{account} va a bajar
bank_fees: Comisiones en %{account}
+ fixed_commitments_ratio:
+ up: Tus compromisos fijos pesan más en tus ingresos
+ over_half: Tus compromisos fijos ya se llevan la mitad o más de tus ingresos
templates:
spending_anomaly:
above: Vas camino de gastar %{projected_spend} en %{category} este mes, aproximadamente un %{deviation_pct}% más que tu promedio mensual reciente de %{baseline_spend}.
@@ -134,3 +140,10 @@ es:
bank_fees:
recurring: "%{account} acumula %{amount} en comisiones en los últimos %{days} días."
new: "%{account} acumula %{amount} en comisiones en los últimos %{days} días, y ninguna en los %{days} días anteriores."
+ fixed_commitments_ratio: "Tus compromisos recurrentes, %{commitments} al mes, se llevan el %{current_ratio}% de tus ingresos mensuales habituales (%{income}), frente al %{previous_ratio}% de hace seis meses. %{explanation}"
+ fixed_commitments_ratio:
+ contributors: "Lo que más ha cambiado: %{list}."
+ contributor:
+ new: "%{name} (pago nuevo, %{amount} al mes)"
+ raised: "%{name} (%{amount} más al mes)"
+ income_fell: Tus ingresos mensuales habituales han bajado de %{previous_income} a %{current_income}.
diff --git a/test/controllers/recurring_transactions_controller_test.rb b/test/controllers/recurring_transactions_controller_test.rb
index 1015a60258..ba79a72ca5 100644
--- a/test/controllers/recurring_transactions_controller_test.rb
+++ b/test/controllers/recurring_transactions_controller_test.rb
@@ -116,6 +116,18 @@ class RecurringTransactionsControllerTest < ActionDispatch::IntegrationTest
assert_equal 15.99, @recurring_transaction.reload.amount
end
+ # Editing the amount is how a rent rise is declared, so the old price has to
+ # stay in history for anything comparing against an earlier date.
+ test "update keeps the previous amount in the bill's price history" do
+ patch recurring_transaction_url(@recurring_transaction),
+ params: { recurring_transaction: { name: @recurring_transaction.display_name, amount: "17.99" } }
+
+ @recurring_transaction.reload
+ assert_equal 17.99, @recurring_transaction.amount
+ assert_equal 15.99, @recurring_transaction.amount_on(6.months.ago.to_date)
+ assert @recurring_transaction.recurring_price_changes.sole.recorded_by_user?
+ end
+
test "the amount steps by the currency, never finer than the column" do
assert_in_delta 0.01, RecurringTransaction.amount_step("USD")
assert_in_delta 1.0, RecurringTransaction.amount_step("JPY")
diff --git a/test/helpers/insights_helper_test.rb b/test/helpers/insights_helper_test.rb
index d7979cffe0..7aa986dc52 100644
--- a/test/helpers/insights_helper_test.rb
+++ b/test/helpers/insights_helper_test.rb
@@ -300,6 +300,15 @@ class InsightsHelperTest < ActionView::TestCase
assert_not insight_dig_in_available?(insight)
end
+ test "fixed commitments ratio warns, leads with the ratio and links to recurring transactions" do
+ insight = build_insight("fixed_commitments_ratio", metadata: { "current_ratio" => 35.0, "previous_ratio" => 30.0 },
+ facts: { "current_ratio" => "35.0" })
+
+ assert_equal :warning, insight_sentiment(insight)
+ assert_equal [ "35.0%", "of income" ], insight_key_figure(insight)
+ assert_equal recurring_transactions_path, insight_action(insight)[:href]
+ end
+
test "loan payment change reads its direction for sentiment and leads with the new payment" do
up = build_insight("loan_payment_change",
metadata: { "account_id" => accounts(:loan).id, "previous_payment" => 1424.0, "new_payment" => 1616.0 },
diff --git a/test/models/insight/generators/fixed_commitments_ratio_generator_test.rb b/test/models/insight/generators/fixed_commitments_ratio_generator_test.rb
new file mode 100644
index 0000000000..43f73f4e62
--- /dev/null
+++ b/test/models/insight/generators/fixed_commitments_ratio_generator_test.rb
@@ -0,0 +1,465 @@
+require "test_helper"
+
+class Insight::Generators::FixedCommitmentsRatioGeneratorTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ travel_to Date.new(2026, 11, 16)
+ @family = families(:dylan_family)
+ # `depository` is shared with every member; `connected` is private to the admin.
+ @shared = accounts(:depository)
+ @private = accounts(:connected)
+
+ Entry.where(account_id: @family.accounts.select(:id), entryable_type: "Transaction").delete_all
+ @family.recurring_transactions.destroy_all
+ end
+
+ test "flags commitments rising exactly the threshold against six months ago" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+
+ insight = generate.sole
+
+ assert_equal "fixed_commitments_ratio", insight.insight_type
+ assert_equal "fixed_commitments_ratio", insight.dedup_key
+ assert_equal "medium", insight.priority
+ assert_equal 35, insight.metadata[:current_band]
+ assert insight.metadata[:accounts_digest].present?
+ assert_equal "35.0", insight.facts[:current_ratio]
+ assert_equal "30.0", insight.facts[:previous_ratio]
+ assert_includes insight.facts[:explanation], "Gym (new"
+ assert_not_includes insight.facts[:explanation], "Rent"
+ end
+
+ test "stays quiet just under the rise threshold" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 199.6, since: 2.months.ago)
+
+ assert_empty generate
+ end
+
+ test "flags crossing half of income even when the rise is small" do
+ monthly_income(4_000)
+ commitment("Rent", 1_900, since: 2.years.ago)
+ commitment("Phone", 100, since: 2.months.ago)
+
+ insight = generate.sole
+
+ assert_equal "high", insight.priority
+ assert_equal I18n.t("insights.titles.fixed_commitments_ratio.over_half"), insight.title
+ assert_equal "50.0", insight.facts[:current_ratio]
+ end
+
+ test "stays quiet just under half of income" do
+ monthly_income(4_000)
+ commitment("Rent", 1_900, since: 2.years.ago)
+ commitment("Phone", 96, since: 2.months.ago)
+
+ assert_empty generate
+ end
+
+ test "stays quiet when commitments were already above half six months ago" do
+ monthly_income(4_000)
+ commitment("Rent", 2_400, since: 2.years.ago)
+ commitment("Phone", 100, since: 2.months.ago)
+
+ assert_empty generate
+ end
+
+ # Rent paid for years but declared today: history is backfilled for six
+ # months only, so its first occurrence lands at the edge of that window.
+ test "a long-standing bill declared today with backfilled history is not new" do
+ monthly_income(4_000)
+ rent = commitment("Rent", 1_600, since: Date.current, manual: true)
+ RecurringTransaction::OccurrenceGenerator.new(rent).backfill!(from: 6.months.ago.to_date)
+
+ assert_empty generate
+ end
+
+ test "a bill declared going forward says nothing about before and is not new" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ declared = commitment("Insurance", 400, since: Date.current)
+ declared.update_columns(anchor_date: Date.current.next_month.beginning_of_month)
+
+ assert_empty generate
+ end
+
+ test "a declared bill with a past first due date is new from that date" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ declared = commitment("Insurance", 200, since: Date.current)
+ declared.update_columns(anchor_date: 2.months.ago.to_date)
+
+ assert_includes generate.sole.facts[:explanation], "Insurance (new"
+ end
+
+ test "returns nothing when no commitment was in force six months ago" do
+ monthly_income(4_000)
+ commitment("Gym", 1_000, since: 2.months.ago)
+
+ assert_empty generate
+ end
+
+ test "a price rise counts as a contributor with the amount it added" do
+ monthly_income(4_000)
+ rent = commitment("Rent", 1_400, since: 2.years.ago)
+ rent.recurring_price_changes.create!(effective_on: 3.months.ago.to_date, previous_amount: 1_200,
+ new_amount: 1_400, currency: "USD", source: "user")
+
+ insight = generate.sole
+
+ assert_equal "35.0", insight.facts[:current_ratio]
+ assert_equal "30.0", insight.facts[:previous_ratio]
+ assert_includes insight.facts[:explanation], "Rent ($200.00 a month more)"
+ end
+
+ test "a rent raised by editing the bill counts as a rise" do
+ monthly_income(4_000)
+ rent = commitment("Rent", 1_200, since: 2.years.ago)
+
+ rent.update!(amount: 1_400)
+
+ insight = generate.sole
+ assert_equal "35.0", insight.facts[:current_ratio]
+ assert_equal "30.0", insight.facts[:previous_ratio]
+ end
+
+ test "a series that replaced another reads as raised, not new" do
+ monthly_income(4_000)
+ commitment("Rent", 1_000, since: 2.years.ago)
+ old_plan = commitment("Phone plan", 200, since: 2.years.ago, status: "ended",
+ cancelled_on: 2.months.ago.to_date, last_occurrence_date: 2.months.ago.to_date)
+ new_plan = commitment("Phone plan v2", 400, since: 2.months.ago)
+ old_plan.update_columns(replaced_by_id: new_plan.id)
+
+ assert_includes generate.sole.facts[:explanation], "Phone plan v2 ($200.00 a month more)"
+ end
+
+ test "a series that ended since counts six months ago, so a swap is not a rise" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Old gym", 200, since: 2.years.ago, status: "ended", cancelled_on: 2.months.ago.to_date,
+ last_occurrence_date: 2.months.ago.to_date)
+ commitment("New gym", 200, since: 2.months.ago)
+
+ assert_empty generate
+ end
+
+ # Today: rent + gym = 1,600 (40%). Six months ago: rent + club + magazine
+ # = 1,800 (45%). Without them back then this would read as a 10-point rise.
+ test "a series paused or gone stale since counts six months ago but not today" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 400, since: 2.months.ago)
+ commitment("Paused club", 400, since: 2.years.ago, status: "paused", last_occurrence_date: 3.months.ago.to_date)
+ commitment("Stale magazine", 200, since: 2.years.ago, status: "inactive", last_occurrence_date: 3.months.ago.to_date)
+
+ assert_empty generate
+ end
+
+ test "a series that stopped before six months ago counts on neither side" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+ commitment("Paused club", 400, since: 2.years.ago, status: "paused", last_occurrence_date: 8.months.ago.to_date)
+
+ insight = generate.sole
+
+ assert_equal "35.0", insight.facts[:current_ratio]
+ assert_equal "30.0", insight.facts[:previous_ratio]
+ end
+
+ # An annual bill's previous payment can sit beyond the backfilled history,
+ # so one first seen two months ago is the edge of that history, not new.
+ test "a dismissed suggestion never counts six months ago" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+ dismissed = commitment("Detected club", 400, since: 2.years.ago, status: "ended",
+ last_occurrence_date: 2.months.ago.to_date)
+ dismissed.recurring_occurrences.delete_all
+
+ insight = generate.sole
+
+ assert_equal "30.0", insight.facts[:previous_ratio]
+ end
+
+ # A pause records no date, and the last payment of an annual bill can sit
+ # months before the reference date while the bill was still in force.
+ test "a paused annual bill counts six months ago through the cycle its last payment covers" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+ insurance = commitment("Insurance", 2_400, since: 2.years.ago, status: "paused",
+ last_occurrence_date: Date.new(2026, 1, 1))
+ RecurringTransaction::FrequencyPreset.apply(insurance, preset: "annual", day_of_month: "1", month_of_year: "1")
+ insurance.save!
+
+ # Six months ago 1,200 + 200 a month of insurance = 35%; today 1,400 = 35%.
+ assert_empty generate
+ end
+
+ test "prices six months ago on the last day of the earlier window, even in a shorter month" do
+ travel_to Date.new(2026, 5, 16)
+ monthly_income(4_000)
+ rent = commitment("Rent", 1_400, since: 2.years.ago)
+ # The earlier window ends on 31 October 2025; shifting 30 April back six
+ # months lands on 30 October instead.
+ rent.recurring_price_changes.create!(effective_on: Date.new(2025, 10, 31), previous_amount: 1_200,
+ new_amount: 1_400, currency: "USD", source: "user")
+
+ assert_empty generate
+ end
+
+ test "an acknowledged rise does not reopen when the ratio falls into a lower band" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+ @family.insights.create!(insight_type: "fixed_commitments_ratio", priority: "medium", status: "dismissed",
+ title: "t", body: "b", dedup_key: "fixed_commitments_ratio",
+ metadata: { "current_band" => 40 }, generated_at: 1.hour.ago)
+
+ assert_equal 40, generate.sole.metadata[:current_band]
+ end
+
+ # An acknowledged row is not expired when its condition clears, so the
+ # last time the job regenerated it is what says whether the rise stayed live.
+ test "a rise that cleared after being acknowledged comes back visible at a lower band" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+ acknowledged = @family.insights.create!(insight_type: "fixed_commitments_ratio", priority: "medium",
+ status: "dismissed", title: "t", body: "b", dedup_key: "fixed_commitments_ratio",
+ metadata: { "current_band" => 40 }, generated_at: 3.days.ago)
+ @family.users.each { |user| user.update!(preferences: (user.preferences || {}).merge("preview_features_enabled" => true)) }
+
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+
+ assert acknowledged.reload.active?
+ assert_equal 35, acknowledged.metadata["current_band"]
+ end
+
+ test "a rise that cleared after being acknowledged comes back visible in the same band" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+ acknowledged = travel_to(3.days.ago) do
+ @family.insights.create!(insight_type: "fixed_commitments_ratio", priority: "medium",
+ status: "dismissed", title: "t", body: "b", dedup_key: "fixed_commitments_ratio",
+ metadata: JSON.parse(generate.sole.metadata.to_json), generated_at: Time.current)
+ end
+ @family.users.each { |user| user.update!(preferences: (user.preferences || {}).merge("preview_features_enabled" => true)) }
+
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+
+ assert acknowledged.reload.active?
+ assert_equal 35, acknowledged.metadata["current_band"]
+ end
+
+ test "an acknowledged rise that stays live keeps its metadata" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+ acknowledged = travel_to(1.day.ago) do
+ @family.insights.create!(insight_type: "fixed_commitments_ratio", priority: "medium",
+ status: "dismissed", title: "t", body: "b", dedup_key: "fixed_commitments_ratio",
+ metadata: JSON.parse(generate.sole.metadata.to_json), generated_at: Time.current)
+ end
+
+ assert_equal acknowledged.metadata, JSON.parse(generate.sole.metadata.to_json)
+ end
+
+ test "an expired rise starts again from the current band" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+ @family.insights.create!(insight_type: "fixed_commitments_ratio", priority: "medium", status: "expired",
+ title: "t", body: "b", dedup_key: "fixed_commitments_ratio",
+ metadata: { "current_band" => 40 }, generated_at: 1.month.ago)
+
+ assert_equal 35, generate.sole.metadata[:current_band]
+ end
+
+ test "normalises annual and weekly cadences to a month" do
+ monthly_income(4_000)
+ commitment("Rent", 1_000, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+ insurance = commitment("Insurance", 2_400, since: 2.months.ago)
+ RecurringTransaction::FrequencyPreset.apply(insurance, preset: "annual", day_of_month: "1", month_of_year: "9")
+ insurance.save!
+ cleaner = commitment("Cleaner", 10, since: 2.months.ago)
+ RecurringTransaction::FrequencyPreset.apply(cleaner, preset: "weekly", weekday: "1")
+ cleaner.save!
+
+ insight = generate.sole
+
+ # Today 1,000 + 200 + 2,400 / 12 + 10 × 52.18 / 12 = 1,443.48; then 1,000 + 200.
+ assert_equal "36.1", insight.facts[:current_ratio]
+ assert_equal "30.0", insight.facts[:previous_ratio]
+ assert_includes insight.facts[:explanation], "Cleaner (new, $43.48"
+ assert_not_includes insight.facts[:explanation], "Insurance"
+ end
+
+ test "leaves out a series in a currency without an exchange rate" do
+ ExchangeRate.stubs(:provider).returns(nil)
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+ commitment("Tokyo storage", 50_000, since: 2.months.ago, currency: "JPY")
+
+ assert_equal "35.0", generate.sole.facts[:current_ratio]
+ end
+
+ test "explains a rise caused by lower income" do
+ monthly_income(3_000, months: 1..6)
+ monthly_income(4_000, months: 7..12)
+ commitment("Rent", 1_200, since: 2.years.ago)
+
+ insight = generate.sole
+
+ assert_equal "40.0", insight.facts[:current_ratio]
+ assert_includes insight.facts[:explanation], "$3,000.00"
+ assert_includes insight.facts[:explanation], "$4,000.00"
+ end
+
+ test "mentions income alongside new commitments when it drove at least half the rise" do
+ monthly_income(3_000, months: 1..6)
+ monthly_income(4_000, months: 7..12)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 100, since: 2.months.ago)
+
+ explanation = generate.sole.facts[:explanation]
+
+ assert_includes explanation, "Gym (new"
+ assert_includes explanation, "$3,000.00"
+ end
+
+ test "leaves income out of the explanation when it drove less than half the rise" do
+ monthly_income(3_800, months: 1..6)
+ monthly_income(4_000, months: 7..12)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+
+ explanation = generate.sole.facts[:explanation]
+
+ assert_includes explanation, "Gym (new"
+ assert_not_includes explanation, "$3,800.00"
+ end
+
+ test "uses the median income so a bonus month does not hide the rise" do
+ monthly_income(4_000)
+ income_in(2, 12_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+
+ assert_equal "35.0", generate.sole.facts[:current_ratio]
+ end
+
+ test "leaves out income on an account that is private to one member" do
+ monthly_income(4_000)
+ 6.times { |offset| create_transaction(account: @private, amount: -4_000, name: "Private salary",
+ date: (Date.current.beginning_of_month << (offset + 1)).change(day: 20)) }
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+
+ insight = generate.sole
+
+ assert_equal "35.0", insight.facts[:current_ratio]
+ assert_equal "$4,000.00", insight.facts[:income]
+ end
+
+ test "counts recurring payments into a loan but not into other accounts" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ shared_loan, shared_asset = accounts(:loan), accounts(:other_asset)
+ [ shared_loan, shared_asset ].each do |account|
+ AccountShare.create!(account: account, user: users(:family_member), permission: "read_only")
+ end
+ commitment("Mortgage payment", 400, since: 2.months.ago, destination_account: shared_loan)
+ commitment("Savings sweep", 400, since: 2.months.ago, destination_account: shared_asset)
+
+ assert_equal "40.0", generate.sole.facts[:current_ratio]
+ end
+
+ test "leaves out series on an account that is private to one member" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Private club", 400, since: 2.months.ago, account: @private)
+
+ assert_empty generate
+ end
+
+ test "returns nothing without income six months ago to compare with" do
+ monthly_income(4_000, months: 1..6)
+ commitment("Rent", 1_200, since: 2.years.ago)
+
+ assert_empty generate
+ end
+
+ test "returns nothing without recurring commitments" do
+ monthly_income(4_000)
+
+ assert_empty generate
+ end
+
+ test "returns nothing when recurring transactions are disabled" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 400, since: 2.months.ago)
+ @family.update!(recurring_transactions_disabled: true)
+
+ assert_empty generate
+ end
+
+ test "writes the body in English and Spanish" do
+ monthly_income(4_000)
+ commitment("Rent", 1_200, since: 2.years.ago)
+ commitment("Gym", 200, since: 2.months.ago)
+
+ %i[en es].each do |locale|
+ I18n.with_locale(locale) do
+ insight = generate.sole
+ body = Insight::BodyWriter.new.write(insight)
+
+ assert_includes body, "Gym"
+ assert_includes body, { en: "35.0%", es: "35,0%" }.fetch(locale)
+ assert_no_match(/translation missing/i, body)
+ assert_no_match(/translation missing/i, insight.title)
+ end
+ end
+ end
+
+ private
+ def generate
+ Insight::Generators::FixedCommitmentsRatioGenerator.new(@family).generate
+ end
+
+ # Income on the 15th of each of the given complete months back from today.
+ def monthly_income(amount, months: 1..12)
+ months.each { |offset| income_in(offset, amount) }
+ end
+
+ def income_in(months_ago, amount)
+ create_transaction(account: @shared, amount: -amount, name: "Salary",
+ date: (Date.current.beginning_of_month << months_ago).change(day: 15))
+ end
+
+ # A detected series whose first payment was on `since`. One first paid
+ # before six months ago was already known to Sure then; a recent one was
+ # confirmed today, with its history backfilled from that first payment.
+ def commitment(name, amount, since:, account: @shared, currency: "USD", **attributes)
+ since = since.to_date
+ series = @family.recurring_transactions.create!(
+ name: name, account: account, amount: amount, currency: currency, expected_day_of_month: 1,
+ last_occurrence_date: Date.current.beginning_of_month, next_expected_date: Date.current.next_month.beginning_of_month,
+ status: "active", manual: false, **attributes
+ )
+ series.update_columns(created_at: since < Date.current << 6 ? since : Time.current)
+ series.recurring_occurrences.delete_all
+ series.recurring_occurrences.create!(family: @family, original_due_on: since, due_on: since, currency: currency)
+ series
+ end
+end
diff --git a/test/models/recurring_transaction/frequency_preset_test.rb b/test/models/recurring_transaction/frequency_preset_test.rb
index 28b7c2151b..253c8f94a1 100644
--- a/test/models/recurring_transaction/frequency_preset_test.rb
+++ b/test/models/recurring_transaction/frequency_preset_test.rb
@@ -229,6 +229,7 @@ class RecurringTransaction::FrequencyPresetTest < ActiveSupport::TestCase
assert_equal due, @recurring.next_expected_date
assert @recurring.one_off?
assert_equal 0, @recurring.monthly_equivalent_amount.amount
+ assert_equal 0, @recurring.monthly_equivalent_amount(on: 1.year.ago.to_date).amount
found = Preset.detect(@recurring)
assert_equal [ "once", due ], [ found.key, found.once_on ]
diff --git a/test/models/recurring_transaction_test.rb b/test/models/recurring_transaction_test.rb
index 975265a3fa..a474bb7336 100644
--- a/test/models/recurring_transaction_test.rb
+++ b/test/models/recurring_transaction_test.rb
@@ -1860,7 +1860,122 @@ class RecurringTransactionTest < ActiveSupport::TestCase
assert_equal "LEGACY CO", bill.reload.matcher_name
end
+ test "amount_on reads the price in force on a date from the price history" do
+ series = @family.recurring_transactions.create!(
+ name: "Rent", account: @account, amount: 1_400, currency: "USD",
+ expected_day_of_month: 1, last_occurrence_date: Date.current,
+ next_expected_date: 1.month.from_now.to_date, status: "active", manual: true
+ )
+ series.recurring_price_changes.create!(effective_on: 6.months.ago.to_date, previous_amount: 1_100,
+ new_amount: 1_200, currency: "USD", source: "user")
+ series.recurring_price_changes.create!(effective_on: 2.months.ago.to_date, previous_amount: 1_200,
+ new_amount: 1_400, currency: "USD", source: "user")
+
+ assert_equal 1_100, series.amount_on(1.year.ago.to_date)
+ assert_equal 1_200, series.amount_on(3.months.ago.to_date)
+ assert_equal 1_400, series.amount_on(2.months.ago.to_date)
+ assert_equal 1_400, series.amount_on(Date.current)
+ assert_equal Money.new(1_200, "USD"), series.monthly_equivalent_amount(on: 3.months.ago.to_date)
+ end
+
+ test "editing the amount records the change from today, so the old price stays in history" do
+ rent = create_rent(1_200)
+
+ rent.update!(amount: 1_400)
+
+ change = rent.recurring_price_changes.sole
+ assert_equal [ Date.current, 1_200, 1_400, "USD" ], [ change.effective_on, change.previous_amount, change.new_amount, change.currency ]
+ assert change.recorded_by_user?
+ assert_equal 1_200, rent.amount_on(Date.yesterday)
+ assert_equal 1_400, rent.amount_on(Date.current)
+ end
+
+ test "a second edit on the same day moves that day's change, and undoing it removes the change" do
+ rent = create_rent(1_200)
+
+ rent.update!(amount: 1_300)
+ rent.update!(amount: 1_400)
+ assert_equal [ 1_200, 1_400 ], [ rent.recurring_price_changes.sole.previous_amount, rent.recurring_price_changes.sole.new_amount ]
+
+ rent.update!(amount: 1_200)
+ assert_empty rent.recurring_price_changes.reload
+ end
+
+ test "an edit on the day of a detected change takes that change over" do
+ rent = create_rent(1_200)
+ rent.recurring_price_changes.create!(effective_on: Date.current, previous_amount: 1_200, new_amount: 1_300,
+ currency: "USD", source: "detected")
+ rent.update!(amount: 1_300)
+ rent.update!(amount: 1_400)
+
+ travel_to(Date.tomorrow) { rent.update!(amount: 1_300) }
+
+ today = rent.recurring_price_changes.find_by!(effective_on: Date.current)
+ assert_equal [ 1_200, 1_400 ], [ today.previous_amount, today.new_amount ]
+ assert today.recorded_by_user?
+ assert_equal 1_400, rent.reload.amount_on(Date.current)
+ assert_equal 1_300, rent.amount_on(Date.tomorrow)
+ end
+
+ test "an amount the price history already reached records nothing more" do
+ rent = create_rent(1_200)
+ rent.recurring_price_changes.create!(effective_on: 1.week.ago.to_date, previous_amount: 1_200, new_amount: 1_400,
+ currency: "USD", source: "detected")
+
+ rent.update!(amount: 1_400)
+
+ assert_equal 1, rent.recurring_price_changes.count
+ end
+
+ test "a change of currency, sign or a suggestion's amount is not a price change" do
+ rent = create_rent(1_200)
+ rent.update!(amount: 1_000, currency: "EUR")
+ suggestion = create_rent(50, name: "Gym", status: "suggested")
+ suggestion.update!(amount: 60)
+ income = create_rent(-2_000, name: "Salary", bill_type: "income")
+ income.update!(amount: -2_200)
+
+ assert_empty RecurringPriceChange.where(recurring_transaction: [ rent, suggestion, income ])
+ end
+
+ test "obligations keeps expenses and payments into the given debt types, whatever the status" do
+ expense = build_recurring(name: "Rent", status: "paused").tap(&:save!)
+ into_loan = create_transfer_series("Mortgage", accounts(:loan))
+ into_card = create_transfer_series("Card payment", accounts(:credit_card))
+
+ results = @family.recurring_transactions.obligations(%w[Loan])
+
+ assert_includes results, expense
+ assert_includes results, into_loan
+ assert_not_includes results, into_card
+ assert_includes @family.recurring_transactions.obligations(%w[CreditCard Loan]), into_card
+ end
+
+ test "within_accounts keeps series whose every endpoint is in the given accounts" do
+ shared = accounts(:depository)
+ private_account = accounts(:connected)
+ on_shared = @family.recurring_transactions.create!(
+ name: "Shared bill", account: shared, amount: 10, currency: "USD", expected_day_of_month: 1,
+ last_occurrence_date: Date.current, next_expected_date: 1.month.from_now.to_date, status: "active", manual: true
+ )
+ on_private = on_shared.dup.tap { |series| series.update!(name: "Private bill", account: private_account) }
+ without_account = on_shared.dup.tap { |series| series.update!(name: "Legacy bill", account: nil) }
+
+ results = @family.recurring_transactions.within_accounts(Account.where(id: shared.id))
+
+ assert_includes results, on_shared
+ assert_includes results, without_account
+ assert_not_includes results, on_private
+ end
+
private
+ def create_rent(amount, name: "Rent", **attributes)
+ @family.recurring_transactions.create!(
+ name: name, account: @account, amount: amount, currency: "USD",
+ expected_day_of_month: 1, last_occurrence_date: Date.current,
+ next_expected_date: 1.month.from_now.to_date, status: "active", manual: true, **attributes
+ )
+ end
def create_transfer_series(name, destination)
@family.recurring_transactions.create!(