Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add a fees insight per account (#5197)

David Gile379c35ad8b9
diff --git a/app/helpers/insights_helper.rb b/app/helpers/insights_helper.rb
index 394ffe6440..49c5ba9f8e 100644
--- a/app/helpers/insights_helper.rb
+++ b/app/helpers/insights_helper.rb
@@ -12,7 +12,8 @@ module InsightsHelper
# the same object seen from two places.
"maintained_goal_depleted" => "shield-alert",
"bill_not_covered" => "calendar-x",
- "loan_payment_change" => "landmark"
+ "loan_payment_change" => "landmark",
+ "bank_fees" => "receipt"
}.freeze
def insight_icon_key(insight)
@@ -87,6 +88,8 @@ module InsightsHelper
facts["shortfall"] && [ facts["shortfall"], t("insights.figures.short_on", date: facts["due_on"]) ]
when "loan_payment_change"
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) ]
end
end
@@ -107,6 +110,13 @@ module InsightsHelper
when "idle_cash", "bill_not_covered", "loan_payment_change"
account = insight_account(insight)
account && { text: t("insights.actions.#{insight.insight_type}"), href: account_path(account) }
+ when "bank_fees"
+ account = insight_account(insight)
+ fee_names = insight.family.categories.fees.pluck(:name)
+ return nil unless account && fee_names.any? && insight.period_start && insight.period_end
+ { text: t("insights.actions.bank_fees"),
+ href: transactions_path(q: { account_ids: [ account.id ], categories: fee_names, status: [ "confirmed" ], types: [ "expense", "income" ],
+ 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"
@@ -192,7 +202,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"
+ when "budget_at_risk", "maintained_goal_depleted", "bank_fees"
# 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/category.rb b/app/models/category.rb
index 93f635bf7c..a69fc0ab49 100644
--- a/app/models/category.rb
+++ b/app/models/category.rb
@@ -46,6 +46,10 @@ class Category < ApplicationRecord
.order(:name, :id)
}
scope :roots, -> { where(parent_id: nil) }
+ # The default Fees category. Its stored name is in the locale active when it
+ # was created, which can be any member's (transfer fees create it under the
+ # request's locale), so every supported locale's name counts.
+ scope :fees, -> { where(name: LanguagesHelper::SUPPORTED_LOCALES.map { |locale| I18n.t(FEES_NAME_KEY, locale: locale) }.uniq) }
# Legacy scopes - classification removed; these now return all categories
scope :incomes, -> { all }
scope :expenses, -> { all }
@@ -111,6 +115,7 @@ class Category < ApplicationRecord
UNCATEGORIZED_NAME_KEY = "models.category.uncategorized"
OTHER_INVESTMENTS_NAME_KEY = "models.category.other_investments"
INVESTMENT_CONTRIBUTIONS_NAME_KEY = "models.category.investment_contributions"
+ FEES_NAME_KEY = "models.category.defaults.fees"
DEFAULT_CATEGORY_TRANSLATION_KEYS = %w[
income
food_and_drink
diff --git a/app/models/insight.rb b/app/models/insight.rb
index 2f8518e3a2..5c6200d6bc 100644
--- a/app/models/insight.rb
+++ b/app/models/insight.rb
@@ -29,6 +29,7 @@ class Insight < ApplicationRecord
maintained_goal_depleted
bill_not_covered
loan_payment_change
+ bank_fees
].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 f13d8616a0..6582fa953a 100644
--- a/app/models/insight/generator_registry.rb
+++ b/app/models/insight/generator_registry.rb
@@ -14,7 +14,8 @@ class Insight::GeneratorRegistry
Insight::Generators::BudgetInsightGenerator,
Insight::Generators::MaintainedGoalDepletedGenerator,
Insight::Generators::BillNotCoveredGenerator,
- Insight::Generators::LoanRepaymentChangeGenerator
+ Insight::Generators::LoanRepaymentChangeGenerator,
+ Insight::Generators::BankFeesGenerator
].freeze
Result = Data.define(:insights, :succeeded_types)
diff --git a/app/models/insight/generators/bank_fees_generator.rb b/app/models/insight/generators/bank_fees_generator.rb
new file mode 100644
index 0000000000..21d79fdd67
--- /dev/null
+++ b/app/models/insight/generators/bank_fees_generator.rb
@@ -0,0 +1,135 @@
+# Adds up the fees each bank account was charged over the last 90 days:
+# transactions in the default Fees category or its subcategories, refunds
+# netted out. One insight per account, when the total reaches MIN_TOTAL or
+# when the account charged a fee after charging none in the 90 days before
+# (only for an account whose history covers those 90 days).
+class Insight::Generators::BankFeesGenerator < Insight::Generator
+ produces "bank_fees"
+
+ # Known limitation: family-currency units, tuned for dollar/euro-scale
+ # currencies (¥10 would flag almost any fee).
+ MIN_TOTAL = 10
+ WINDOW_DAYS = 90
+ # Accounts a bank charges fees on. Brokerage and crypto fees are the cost of
+ # trading, which the portfolio reports, not something the bank charged.
+ ACCOUNT_TYPES = %w[Depository CreditCard Loan].freeze
+
+ FeeTotals = Data.define(:account_id, :total, :charges, :latest_fee_id, :prior_charges, :first_fees) do
+ alias_method :first_fees?, :first_fees
+ end
+
+ def generate
+ category_ids = fee_category_ids
+ return [] if category_ids.empty?
+
+ fees = fee_entries(category_ids)
+ totals = with_first_fees(fee_totals(fees)).select { |row| reportable?(row) }
+ return [] if totals.empty?
+
+ accounts = eligible_accounts.where(id: totals.map(&:account_id)).index_by(&:id)
+
+ totals.filter_map do |row|
+ account = accounts[row.account_id]
+ next unless account
+
+ build_insight(
+ insight_type: "bank_fees",
+ priority: row.first_fees? ? "medium" : "low",
+ title: I18n.t("insights.titles.bank_fees", account: account.name),
+ template_key: row.first_fees? ? "bank_fees.new" : "bank_fees.recurring",
+ facts: {
+ account: account.name,
+ amount: format_money(row.total),
+ count: row.charges,
+ days: WINDOW_DAYS
+ },
+ # The total drifts as old fees roll out of the window; only a new fee
+ # (or the account turning from "first fees" into a repeat) is a change
+ # worth resurfacing an acknowledged card for. The fee recorded last
+ # (not the one dated last) catches a second fee on the same day and a
+ # fee imported late with an older date; it is read without a date
+ # window, so a fee ageing out never passes for a new one.
+ metadata: {
+ account_id: account.id,
+ latest_fee_id: row.latest_fee_id,
+ new: row.first_fees?
+ },
+ period: Period.custom(start_date: window_start, end_date: Date.current),
+ dedup_key: "bank_fees:#{account.id}"
+ )
+ end
+ end
+
+ private
+ def reportable?(row)
+ return false unless row.total.positive?
+
+ row.total >= MIN_TOTAL || row.first_fees?
+ end
+
+ # The insight names the account and its fees to the whole family, so only
+ # accounts every active member can see qualify.
+ def eligible_accounts
+ shared_accounts.visible.where(accountable_type: ACCOUNT_TYPES, currency: family.currency)
+ end
+
+ def fee_category_ids
+ fees = family.categories.fees
+ family.categories.where(id: fees).or(family.categories.where(parent_id: fees)).pluck(:id)
+ end
+
+ # Fee rows as the insight counts them, on accounts it may name.
+ def fee_entries(category_ids)
+ Transaction.joins(:entry)
+ .excluding_pending
+ .merge(Entry.excluding_split_parents)
+ .where(category_id: category_ids)
+ .where.not(kind: Transaction::TRANSFER_KINDS)
+ .where(entries: { account_id: eligible_accounts.select(:id), excluded: false, currency: family.currency })
+ .where("entries.date <= ?", Date.current)
+ end
+
+ # One grouped query over both windows: the current one is summed (so a
+ # refunded fee nets out), the prior one only needs to know whether any fee
+ # was charged at all.
+ def fee_totals(fees)
+ current = ActiveRecord::Base.sanitize_sql_array([ "entries.date >= ?", window_start ])
+ latest_fee_ids = latest_fee_ids(fees)
+
+ fees.where("entries.date >= ?", window_start - WINDOW_DAYS)
+ .group("entries.account_id")
+ .pluck(
+ Arel.sql("entries.account_id"),
+ Arel.sql("COALESCE(SUM(entries.amount) FILTER (WHERE #{current}), 0)"),
+ Arel.sql("COUNT(*) FILTER (WHERE #{current} AND entries.amount > 0)"),
+ Arel.sql("COUNT(*) FILTER (WHERE NOT (#{current}) AND entries.amount > 0)")
+ )
+ .map do |account_id, total, charges, prior_charges|
+ FeeTotals.new(account_id, total, charges, latest_fee_ids[account_id], prior_charges, false)
+ end
+ end
+
+ # Each account's fee recorded last, whatever its date.
+ def latest_fee_ids(fees)
+ fees.where("entries.amount > 0")
+ .group("entries.account_id")
+ .pluck(Arel.sql("entries.account_id"), Arel.sql("(ARRAY_AGG(entries.id ORDER BY entries.created_at DESC, entries.id DESC))[1]"))
+ .to_h
+ end
+
+ # "None in the 90 days before" only means something if the account was
+ # there to be charged: a newly added account has no prior window at all.
+ def with_first_fees(totals)
+ history_starts = Entry.where(account_id: totals.map(&:account_id)).group(:account_id).minimum(:date)
+ covered_since = window_start - WINDOW_DAYS
+
+ totals.map do |row|
+ history_start = history_starts[row.account_id]
+ row.with(first_fees: row.prior_charges.zero? && history_start.present? && history_start <= covered_since)
+ end
+ end
+
+ def window_start
+ Date.current - WINDOW_DAYS
+ end
+end
diff --git a/config/locales/views/insights/en.yml b/config/locales/views/insights/en.yml
index bd3496138c..cf5ad8dc1d 100644
--- a/config/locales/views/insights/en.yml
+++ b/config/locales/views/insights/en.yml
@@ -48,6 +48,7 @@ en:
maintained_goal_depleted: Reserve
bill_not_covered: Bills
loan_payment_change: Loan payment
+ bank_fees: Fees
meta:
next_n_days:
one: Next day
@@ -69,6 +70,9 @@ en:
one: idle %{count} day
other: idle %{count} days
short_on: short on %{date}
+ fee_charges:
+ one: "%{count} charge"
+ other: "%{count} charges"
actions:
spending_anomaly: View %{category} transactions
cash_flow_warning: Review recurring transactions
@@ -80,6 +84,7 @@ en:
maintained_goal_depleted: View reserve
bill_not_covered: Go to account
loan_payment_change: View loan
+ bank_fees: View fees
titles:
spending_anomaly:
above: "%{category} spending is trending up"
@@ -102,6 +107,7 @@ en:
loan_payment_change:
up: "%{account} payment is going up"
down: "%{account} payment is going down"
+ bank_fees: Fees on %{account}
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}.
@@ -125,3 +131,6 @@ en:
loan_payment_change:
up: "Your %{account} payment changes from %{previous_payment} to %{new_payment} on %{effective_on}, %{change_pct}% more, according to the loan's schedule and its recorded rates."
down: "Your %{account} payment changes from %{previous_payment} to %{new_payment} on %{effective_on}, %{change_pct}% less, according to the loan's schedule and its recorded rates."
+ 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."
diff --git a/config/locales/views/insights/es.yml b/config/locales/views/insights/es.yml
index e245640ba1..b2eb2e1444 100644
--- a/config/locales/views/insights/es.yml
+++ b/config/locales/views/insights/es.yml
@@ -48,6 +48,7 @@ es:
maintained_goal_depleted: Reserva
bill_not_covered: Recibos
loan_payment_change: Cuota del préstamo
+ bank_fees: Comisiones
meta:
next_n_days:
one: Próximo día
@@ -69,6 +70,9 @@ es:
one: "%{count} día inactivo"
other: "%{count} días inactivos"
short_on: faltarán el %{date}
+ fee_charges:
+ one: "%{count} cargo"
+ other: "%{count} cargos"
actions:
spending_anomaly: Ver transacciones de %{category}
cash_flow_warning: Revisar transacciones recurrentes
@@ -80,6 +84,7 @@ es:
maintained_goal_depleted: Ver reserva
bill_not_covered: Ir a la cuenta
loan_payment_change: Ver préstamo
+ bank_fees: Ver comisiones
titles:
spending_anomaly:
above: El gasto en %{category} va en aumento
@@ -102,6 +107,7 @@ es:
loan_payment_change:
up: La cuota de %{account} va a subir
down: La cuota de %{account} va a bajar
+ bank_fees: Comisiones en %{account}
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}.
@@ -125,3 +131,6 @@ es:
loan_payment_change:
up: "La cuota de %{account} pasa de %{previous_payment} a %{new_payment} el %{effective_on}, un %{change_pct}% más, según el cuadro de amortización y los tipos registrados."
down: "La cuota de %{account} pasa de %{previous_payment} a %{new_payment} el %{effective_on}, un %{change_pct}% menos, según el cuadro de amortización y los tipos registrados."
+ 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."
diff --git a/test/helpers/insights_helper_test.rb b/test/helpers/insights_helper_test.rb
index 4cb2de8ced..d7979cffe0 100644
--- a/test/helpers/insights_helper_test.rb
+++ b/test/helpers/insights_helper_test.rb
@@ -205,6 +205,24 @@ class InsightsHelperTest < ActionView::TestCase
assert_nil insight_action(dangling)
end
+ test "bank fees warn" do
+ assert_equal "warning", insight_icon_color(build_insight("bank_fees"))
+ end
+
+ test "bank fees lead with the total and link to that account's fees in the window" do
+ family = families(:dylan_family)
+ account = accounts(:depository)
+ family.categories.create!(name: "Fees", color: "#6b7280", lucide_icon: "receipt")
+ insight = build_insight("bank_fees",
+ metadata: { "account_id" => account.id },
+ facts: { "amount" => "$36.00", "count" => 3 },
+ period_start: Date.new(2026, 8, 18), period_end: Date.new(2026, 11, 16))
+
+ assert_equal [ "$36.00", "3 charges" ], insight_key_figure(insight)
+ assert_equal transactions_path(q: { account_ids: [ account.id ], categories: [ "Fees" ], status: [ "confirmed" ], types: [ "expense", "income" ], start_date: "2026-08-18", end_date: "2026-11-16" }),
+ insight_action(insight)[:href]
+ end
+
test "an uncovered bill renders destructive" do
assert_equal "destructive", insight_icon_color(build_insight("bill_not_covered", priority: "high"))
end
diff --git a/test/models/insight/body_writer_test.rb b/test/models/insight/body_writer_test.rb
index ab311e18f0..53fd77cb56 100644
--- a/test/models/insight/body_writer_test.rb
+++ b/test/models/insight/body_writer_test.rb
@@ -52,6 +52,13 @@ class Insight::BodyWriterTest < ActiveSupport::TestCase
end
end
+ test "bank fees have Spanish copy of their own" do
+ TEMPLATE_FACTS.slice("bank_fees.recurring", "bank_fees.new").each do |template_key, facts|
+ assert I18n.exists?("insights.templates.#{template_key}", :es, fallback: false), "missing es copy for #{template_key}"
+ assert I18n.t!("insights.templates.#{template_key}", locale: :es, **facts).present?
+ end
+ end
+
private
# One representative facts hash per template a generator can emit. Keeps
# the i18n templates honest: a renamed key or interpolation raises here
@@ -70,7 +77,9 @@ class Insight::BodyWriterTest < ActiveSupport::TestCase
"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 },
- "bill_not_covered" => { name: "Rent", amount: "$1,460.00", due_on: "Dec 7, 2026", account: "Joint account", shortfall: "$300.00" }
+ "bill_not_covered" => { name: "Rent", amount: "$1,460.00", due_on: "Dec 7, 2026", account: "Joint account", shortfall: "$300.00" },
+ "bank_fees.recurring" => { account: "Checking", amount: "$36.00", count: 3, days: 90 },
+ "bank_fees.new" => { account: "Checking", amount: "$3.00", count: 1, days: 90 }
}.freeze
def placeholders(text)
diff --git a/test/models/insight/generators/bank_fees_generator_test.rb b/test/models/insight/generators/bank_fees_generator_test.rb
new file mode 100644
index 0000000000..8f3f954066
--- /dev/null
+++ b/test/models/insight/generators/bank_fees_generator_test.rb
@@ -0,0 +1,209 @@
+require "test_helper"
+
+class Insight::Generators::BankFeesGeneratorTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ travel_to Date.new(2026, 11, 16)
+
+ @family = families(:dylan_family)
+ # `depository` is shared with family_member; `connected` is private to
+ # family_admin; `investment` is private too unless a test shares it.
+ @checking = accounts(:depository)
+ @fees = @family.categories.create!(name: I18n.t("models.category.defaults.fees"), color: "#6b7280", lucide_icon: "receipt")
+ # Every account has history from before both windows unless a test says
+ # otherwise, so "no fees before" means the account was there to charge them.
+ @family.accounts.each { |account| history_since(account, 200.days.ago) }
+ end
+
+ test "flags fees at or above the minimum on an account every member can see" do
+ fee(@checking, 12, 70.days.ago)
+ fee(@checking, 12, 40.days.ago)
+ fee(@checking, 12, 10.days.ago)
+ fee(@checking, 5, 120.days.ago) # prior window: this is not a new fee
+
+ insight = generate_for(@checking)
+
+ assert_equal "bank_fees", insight.insight_type
+ assert_equal "bank_fees.recurring", insight.template_key
+ assert_equal "low", insight.priority
+ assert_equal "$36.00", insight.facts[:amount]
+ assert_equal "Checking Account", insight.facts[:account]
+ assert_equal 3, insight.facts[:count]
+ assert_equal "bank_fees:#{@checking.id}", insight.dedup_key
+ assert_equal (Date.current - 90), insight.period_start
+ assert_equal Date.current, insight.period_end
+ assert_equal "Checking Account had $36.00 in fees over the last 90 days.",
+ Insight::BodyWriter.new.write(insight)
+ end
+
+ test "stays quiet below the minimum when the account already charged fees before" do
+ fee(@checking, 4, 20.days.ago)
+ fee(@checking, 4, 100.days.ago)
+
+ assert_nil generate_for(@checking)
+ end
+
+ test "a first fee is flagged below the minimum, at medium priority" do
+ fee(@checking, 3, 5.days.ago)
+
+ insight = generate_for(@checking)
+
+ assert_equal "bank_fees.new", insight.template_key
+ assert_equal "medium", insight.priority
+ assert insight.metadata[:new]
+ end
+
+ test "a small fee on an account without history from before both windows is not a first fee" do
+ Entry.where(account: @checking).delete_all
+ history_since(@checking, 120.days.ago)
+ fee(@checking, 3, 5.days.ago)
+
+ assert_nil generate_for(@checking), "an account that did not exist 180 days ago cannot prove it charged no fees then"
+
+ fee(@checking, 9, 4.days.ago)
+ assert_equal "bank_fees.recurring", generate_for(@checking).template_key, "the minimum still applies"
+ end
+
+ test "the card stays the same across quarters and comes back only with a new fee" do
+ fee(@checking, 12, 20.days.ago)
+ fee(@checking, 1, 100.days.ago)
+ before = generate_for(@checking)
+
+ travel_to Date.new(2027, 1, 2)
+ after = generate_for(@checking)
+
+ assert_equal before.dedup_key, after.dedup_key
+ assert_equal before.metadata, after.metadata
+
+ fee(@checking, 12, Date.current)
+ assert_not_equal before.metadata, generate_for(@checking).metadata
+ end
+
+ test "fees that only fall in the prior window are not flagged" do
+ fee(@checking, 50, 100.days.ago)
+
+ assert_nil generate_for(@checking)
+ end
+
+ test "a refunded fee nets out of the total" do
+ fee(@checking, 15, 30.days.ago)
+ fee(@checking, -15, 25.days.ago)
+ fee(@checking, 4, 100.days.ago)
+
+ assert_nil generate_for(@checking)
+ end
+
+ test "subcategories of Fees count, and so does the Fees category named in the family's locale" do
+ @family.update!(locale: "es")
+ @fees.update!(name: I18n.t("models.category.defaults.fees", locale: :es))
+ overdraft = @family.categories.create!(name: "Overdraft", parent: @fees, color: "#6b7280", lucide_icon: "receipt")
+ fee(@checking, 8, 30.days.ago, category: overdraft)
+ fee(@checking, 8, 20.days.ago)
+ fee(@checking, 1, 100.days.ago)
+
+ assert_equal "$16.00", generate_for(@checking).facts[:amount]
+ end
+
+ # Transfer fees create the category in the locale of whoever made the
+ # transfer, which can be a member's own rather than the family's.
+ test "the Fees category is found under a member's locale too" do
+ @fees.update!(name: I18n.t("models.category.defaults.fees", locale: :fr))
+ fee(@checking, 40, 10.days.ago)
+ fee(@checking, 1, 100.days.ago)
+
+ assert_equal "$40.00", generate_for(@checking).facts[:amount]
+ end
+
+ test "excluded, pending, transfer-kind and split-parent rows are ignored" do
+ fee(@checking, 1, 100.days.ago)
+ fee(@checking, 40, 10.days.ago).update!(excluded: true)
+ pending = fee(@checking, 40, 9.days.ago)
+ pending.entryable.update!(extra: { "plaid" => { "pending" => true } })
+ create_transaction(account: @checking, amount: 40, date: 8.days.ago.to_date, category: @fees, kind: "funds_movement")
+ parent = fee(@checking, 40, 7.days.ago)
+ Entry.create!(account: @checking, parent_entry: parent, name: "Part", date: parent.date, currency: "USD", amount: 40,
+ entryable: Transaction.new(category: categories(:food_and_drink)))
+
+ assert_nil generate_for(@checking)
+ end
+
+ test "investment accounts are left out even when shared with everyone" do
+ investment = accounts(:investment)
+ AccountShare.create!(account: investment, user: users(:family_member), permission: :read_only)
+ fee(investment, 25, 10.days.ago)
+
+ assert_nil generate_for(investment)
+ end
+
+ test "an account private to one member is left out of the shared feed" do
+ private_account = accounts(:connected)
+ fee(private_account, 25, 10.days.ago)
+
+ assert_nil generate_for(private_account)
+
+ users(:family_member).update_columns(active: false)
+ assert_not_nil generate_for(private_account), "an inactive member does not hide an account"
+ end
+
+ test "a fee rolling out of the window does not change the material metadata" do
+ fee(@checking, 12, 85.days.ago)
+ fee(@checking, 1, 100.days.ago)
+ travel 1.second
+ latest = fee(@checking, 12, 10.days.ago)
+ before = generate_for(@checking).metadata
+
+ travel 10.days
+ after = generate_for(@checking).metadata
+
+ assert_equal before, after
+ assert_equal latest.id, after[:latest_fee_id]
+ end
+
+ test "another fee on the same day as the latest one changes the material metadata" do
+ fee(@checking, 12, 10.days.ago)
+ fee(@checking, 1, 100.days.ago)
+ before = generate_for(@checking).metadata
+
+ travel 1.second
+ fee(@checking, 12, 10.days.ago)
+
+ assert_not_equal before, generate_for(@checking).metadata
+ end
+
+ test "the fee recorded last ageing out of both windows does not change the material metadata" do
+ fee(@checking, 12, 10.days.ago)
+ fee(@checking, 1, 100.days.ago)
+ travel 1.second
+ fee(@checking, 2, 175.days.ago)
+ before = generate_for(@checking).metadata
+
+ travel 6.days
+
+ assert_equal before, generate_for(@checking).metadata
+ end
+
+ test "a fee imported late with an older date changes the material metadata" do
+ fee(@checking, 12, 10.days.ago)
+ fee(@checking, 1, 100.days.ago)
+ before = generate_for(@checking).metadata
+
+ travel 1.second
+ fee(@checking, 12, 40.days.ago)
+
+ assert_not_equal before, generate_for(@checking).metadata
+ end
+
+ private
+ def fee(account, amount, date, category: @fees)
+ create_transaction(account: account, amount: amount, date: date.to_date, name: "Maintenance fee", category: category)
+ end
+
+ def history_since(account, date)
+ create_transaction(account: account, amount: 1, date: date.to_date, name: "Opening activity")
+ end
+
+ def generate_for(account)
+ Insight::Generators::BankFeesGenerator.new(@family).generate.find { |insight| insight.metadata[:account_id] == account.id }
+ end
+end