Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Date snoozed bills by their snoozed date in month totals and the plan (#4106)

Guillem Arias Fauste1a166684af12
diff --git a/app/controllers/bills_controller.rb b/app/controllers/bills_controller.rb
index f7f463ab5f..e69f5c0c34 100644
--- a/app/controllers/bills_controller.rb
+++ b/app/controllers/bills_controller.rb
@@ -75,7 +75,9 @@ class BillsController < ApplicationController
.map { |group| group.min_by(&:effective_due_on) }
.sort_by(&:effective_due_on)
- @paid_this_month = closed.select { |occurrence| occurrence.paid? && occurrence.due_on >= today.beginning_of_month }
+ # Paid rows go by the snoozed date too, and stay inside the month: a bill
+ # paid ahead of time lists in the month it is due, not in this one as well.
+ @paid_this_month = closed.select { |occurrence| occurrence.paid? && occurrence.effective_due_on.between?(today.beginning_of_month, month_end) }
compute_kpis(today, month_end)
@@ -88,7 +90,7 @@ class BillsController < ApplicationController
# iterates, which would otherwise be separate queries.
@suggested_series = accessible_suggested_series.includes(:merchant).order(next_expected_date: :asc).load
@has_transaction_history = Current.family.entries.where(entryable_type: "Transaction").exists?
- @suggested_allocations = suggested_allocations(occurrences)
+ @suggested_allocations = suggested_allocations(open_occurrences + @paid_this_month)
# A row waiting on a match decision offers Review rather than Find.
# Already loaded for the queue above, so indexing is free.
@suggestions_by_occurrence = @suggested_allocations.index_by(&:recurring_occurrence_id)
@@ -456,10 +458,11 @@ class BillsController < ApplicationController
def payable_occurrences
# Price changes ride along because bills_attention_reason asks every
# row whether its amount changed recently, and recurrence rules because
- # every row's subline names its schedule.
+ # every row's subline names its schedule. Closed rows count from their
+ # snoozed date, the one index lists them by.
Current.family.recurring_occurrences
.where(recurring_transaction_id: payable_series_ids)
- .where("due_on >= ? OR status = 'scheduled'", Date.current.beginning_of_month)
+ .where("#{RecurringOccurrence::EFFECTIVE_DUE_ON_SQL} >= ? OR status = 'scheduled'", Date.current.beginning_of_month)
.where("due_on <= ?", Date.current + 90)
.includes(recurring_transaction: [ :merchant, :recurring_price_changes, :recurrence_rules ])
.to_a
@@ -599,13 +602,11 @@ class BillsController < ApplicationController
# Ending a bill leaves its scheduled occurrences behind and the matcher
# still scores them, and skipping closes an occurrence but keeps its
# suggestion, so neither may ask about a row the page doesn't show.
- def suggested_allocations(occurrences)
- listed_ids = occurrences.select { |occurrence| occurrence.scheduled? || occurrence.paid? }.map(&:id)
-
+ def suggested_allocations(listed)
RecurringAllocation
.suggested
.joins(recurring_occurrence: :recurring_transaction)
- .where(recurring_occurrence_id: listed_ids)
+ .where(recurring_occurrence_id: listed.map(&:id))
# Income never reviews here: the matcher no longer suggests it, and
# this filter also retires any suggestion written before that rule.
.merge(RecurringTransaction.where.not(bill_type: "income"))
diff --git a/app/models/assistant/function/get_paycheck_plan.rb b/app/models/assistant/function/get_paycheck_plan.rb
index 32bf56f207..c237236e13 100644
--- a/app/models/assistant/function/get_paycheck_plan.rb
+++ b/app/models/assistant/function/get_paycheck_plan.rb
@@ -133,10 +133,13 @@ class Assistant::Function::GetPaycheckPlan < Assistant::Function
}.compact
end
+ # Both dates, as get_bills reports them: the plan files a snoozed bill by
+ # the date it was snoozed to, and record_bill_payment finds it by due_on.
def serialize_item(item)
{
name: item.occurrence.recurring_transaction.display_name,
due_on: item.occurrence.due_on.iso8601,
+ effective_due_on: item.occurrence.effective_due_on.iso8601,
this_period_share: fmt(item.share),
whole_obligation_remaining: fmt(item.remaining_total)
}
diff --git a/app/models/recurring_occurrence.rb b/app/models/recurring_occurrence.rb
index 6a0cacf6ad..fc6a36287e 100644
--- a/app/models/recurring_occurrence.rb
+++ b/app/models/recurring_occurrence.rb
@@ -58,6 +58,10 @@ class RecurringOccurrence < ApplicationRecord
Money.new(resolved_expected_amount, currency)
end
+ # effective_due_on as SQL, for queries that select by it. GREATEST skips a
+ # NULL snoozed_until the way compact does below.
+ EFFECTIVE_DUE_ON_SQL = "GREATEST(recurring_occurrences.due_on, recurring_occurrences.snoozed_until)".freeze
+
# Snoozing postpones the presentation-level due date without rewriting the
# schedule.
def effective_due_on
diff --git a/app/models/recurring_transaction/paycheck_planner.rb b/app/models/recurring_transaction/paycheck_planner.rb
index db707dcaed..b25df0ec9f 100644
--- a/app/models/recurring_transaction/paycheck_planner.rb
+++ b/app/models/recurring_transaction/paycheck_planner.rb
@@ -53,14 +53,15 @@ class RecurringTransaction
cash_on_hand - obligation_total
end
- # Chronological, because both render as a ledger keyed on the due date.
- # `items` itself stays ordered by share, for weight-first callers.
+ # Chronological, because both render as a ledger keyed on the due date,
+ # the snoozed one where a bill was snoozed. `items` itself stays ordered
+ # by share, for weight-first callers.
def items_due
- items.select(&:due_in_period).sort_by { |item| item.occurrence.due_on }
+ items.select(&:due_in_period).sort_by { |item| item.occurrence.effective_due_on }
end
def items_reserved
- items.reject(&:due_in_period).sort_by { |item| item.occurrence.due_on }
+ items.reject(&:due_in_period).sort_by { |item| item.occurrence.effective_due_on }
end
# By what the bill actually costs, not by the slice this period carries.
@@ -178,15 +179,17 @@ class RecurringTransaction
# Chronological, so each window's own bills claim its paycheck before
# any later window's overflow reaches back for the spare.
occurrences = open_payable_occurrences(periods.last[:ends_on])
- .sort_by { |occurrence| [ occurrence.due_on, occurrence.id ] }
+ .sort_by { |occurrence| [ occurrence.effective_due_on, occurrence.id ] }
occurrences.each do |occurrence|
remaining = to_family_currency(occurrence.remaining_amount_money)
next unless remaining.positive?
- # A past-due open occurrence still needs paying; it lands whole in
- # the leading window, since every share of it is already owed.
- effective_due = [ occurrence.due_on, periods.first[:starts_on] ].max
+ # A snoozed bill falls due on the date it was snoozed to, the one the
+ # overview's pay-period markers file it under. A past-due open
+ # occurrence still needs paying; it lands whole in the leading
+ # window, since every share of it is already owed.
+ effective_due = [ occurrence.effective_due_on, periods.first[:starts_on] ].max
home = periods.index { |period| effective_due.between?(period[:starts_on], period[:ends_on]) }
next if home.nil?
@@ -243,7 +246,10 @@ class RecurringTransaction
.or(RecurringTransaction.where(destination_account_id: debt_accounts))
)
.merge(RecurringTransaction.accessible_by(user))
- .where("recurring_occurrences.due_on <= ?", through)
+ # The snoozed date, as apportion_bills reads it. A bill snoozed
+ # past the plan is not one of its bills, not even one it failed
+ # to convert.
+ .where("#{RecurringOccurrence::EFFECTIVE_DUE_ON_SQL} <= ?", through)
.includes(recurring_transaction: :merchant)
.to_a
.tap { |occurrences| preload_confirmed_sums(occurrences) }
diff --git a/app/views/bills/_paycheck_item.html.erb b/app/views/bills/_paycheck_item.html.erb
index 16475e3be0..dfb391f676 100644
--- a/app/views/bills/_paycheck_item.html.erb
+++ b/app/views/bills/_paycheck_item.html.erb
@@ -6,7 +6,7 @@
<div class="flex items-baseline gap-3 py-1">
<span class="w-14 shrink-0 text-xs text-secondary tabular-nums">
- <%= l(item.occurrence.due_on, format: :short) %>
+ <%= l(item.occurrence.effective_due_on, format: :short) %>
</span>
<span class="min-w-0 flex-1 truncate">
diff --git a/test/controllers/bills_controller_test.rb b/test/controllers/bills_controller_test.rb
index 1ee8cd7aa0..ce339984bb 100644
--- a/test/controllers/bills_controller_test.rb
+++ b/test/controllers/bills_controller_test.rb
@@ -362,10 +362,7 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
travel_to Date.current.beginning_of_month + 9.days
create_bill(name: "Soon Co", amount: 20, manual: true, anchor_date: Date.current + 3,
expected_day_of_month: (Date.current + 3).day, next_expected_date: Date.current + 3)
- late = 6.days.ago.to_date
- bill = create_bill(name: "Late Co", amount: 30, expected_day_of_month: late.day,
- last_occurrence_date: 2.months.ago.to_date, next_expected_date: late)
- bill.recurring_occurrences.open_status.order(:due_on).first.snooze!(Date.current + 7)
+ snoozed_late_bill
get bills_url
@@ -377,11 +374,7 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
# month with next month's date on its rail.
test "a bill snoozed past the month's end moves after this month" do
travel_to Date.current.end_of_month - 2.days
- late = 6.days.ago.to_date
- bill = create_bill(name: "Late Co", amount: 30, expected_day_of_month: late.day,
- last_occurrence_date: 2.months.ago.to_date, next_expected_date: late)
- occurrence = bill.recurring_occurrences.open_status.order(:due_on).first
- occurrence.snooze!(Date.current + 7)
+ occurrence = snoozed_late_bill
get bills_url
@@ -390,6 +383,101 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
assert_equal [ occurrence.id ], @controller.view_assigns["later"].map(&:id)
end
+ # Paid, a snoozed bill still belongs to the month of its new date. Paid
+ # before that month, it jumped back into this one with next month's date on
+ # its rail and its payment in this month's paid total, then listed nowhere
+ # once the month turned.
+ test "a bill snoozed into next month and paid early lists as paid in next month" do
+ travel_to Date.current.end_of_month - 2.days
+ occurrence = snoozed_late_bill
+ pay(occurrence)
+
+ get bills_url
+ assert_not_includes @controller.view_assigns["month_rows"].map(&:id), occurrence.id
+ assert_nil @controller.view_assigns["paid_this_month_total"]
+
+ travel_to occurrence.reload.effective_due_on + 1.day
+ get bills_url
+ assert_includes @controller.view_assigns["month_rows"].map(&:id), occurrence.id
+ assert_equal Money.new(30, "USD"), @controller.view_assigns["paid_this_month_total"]
+ end
+
+ # Paid after the month turned, the same bill dropped out of the month it was
+ # snoozed into, because the query still went by the date it was moved from.
+ test "a bill snoozed into next month and paid there stays listed there" do
+ travel_to Date.current.end_of_month - 2.days
+ occurrence = snoozed_late_bill
+ travel_to occurrence.reload.effective_due_on - 2.days
+ pay(occurrence)
+
+ get bills_url
+
+ assert_includes @controller.view_assigns["month_rows"].map(&:id), occurrence.id
+ assert_equal Money.new(30, "USD"), @controller.view_assigns["paid_this_month_total"]
+ end
+
+ # Next month's rent paid a day early used to list, and count as paid, in
+ # both months. It belongs to the month it is due in.
+ test "next month's bill paid early lists in next month only" do
+ travel_to Date.current.end_of_month
+ due = Date.current + 1
+ rent = create_bill(name: "Rent Co", amount: 900, manual: true, anchor_date: due,
+ expected_day_of_month: due.day, next_expected_date: due)
+ occurrence = rent.recurring_occurrences.find_by!(due_on: due)
+ pay(occurrence)
+
+ get bills_url
+ assert_empty @controller.view_assigns["month_rows"]
+ assert_nil @controller.view_assigns["paid_this_month_total"]
+
+ travel_to due + 2.days
+ get bills_url
+ assert_includes @controller.view_assigns["month_rows"].map(&:id), occurrence.id
+ assert_equal Money.new(900, "USD"), @controller.view_assigns["paid_this_month_total"]
+ end
+
+ # The month's first and last days are both inside it: a bill snoozed onto
+ # the 1st and one due on the last day, each paid, list in it.
+ test "paid rows dated on the month's first and last day list in it" do
+ travel_to Date.current.beginning_of_month + 9.days
+ month_start = Date.current.beginning_of_month
+ month_end = Date.current.end_of_month
+ carried = create_bill(name: "Carried Co", amount: 30, expected_day_of_month: (month_start - 5).day,
+ last_occurrence_date: 2.months.ago.to_date, next_expected_date: month_start - 5)
+ first = carried.recurring_occurrences.find_by!(due_on: month_start - 5)
+ first.snooze!(month_start)
+ month_end_bill = create_bill(name: "Month-end Co", amount: 50, manual: true, anchor_date: month_end,
+ expected_day_of_month: month_end.day, next_expected_date: month_end)
+ last = month_end_bill.recurring_occurrences.find_by!(due_on: month_end)
+ pay(first)
+ pay(last)
+
+ get bills_url
+
+ assert_includes @controller.view_assigns["month_rows"].map(&:id), first.id
+ assert_includes @controller.view_assigns["month_rows"].map(&:id), last.id
+ assert_equal Money.new(80, "USD"), @controller.view_assigns["paid_this_month_total"]
+ end
+
+ # The overview files a bill snoozed past payday under that payday's marker.
+ # The income plan kept it before payday, at its old date, and called the
+ # $100 in the bank short.
+ test "the income plan files a bill snoozed past payday under that payday" do
+ @family.accounts.where(accountable_type: "Depository").update_all(balance: 0)
+ accounts(:depository).update_column(:balance, 100)
+ declare_income(name: "Frito Lay", amount: -1200, payday: Date.current + 3)
+ power = declare_bill(name: "Power Co", amount: 120, due: Date.current - 6)
+ occurrence = power.recurring_occurrences.open_status.order(:due_on).first
+ occurrence.snooze!(Date.current + 7)
+
+ get bills_url(view: "paycheck")
+
+ assert_response :success
+ assert_no_match I18n.t("bills.paycheck.shortfall_label"), response.body
+ row = assert_select("a[href=?]", recurring_occurrence_path(occurrence)).first.ancestors("div").first
+ assert_equal I18n.l(Date.current + 7, format: :short), row.at_css("span").text.strip
+ end
+
# On a phone the range squeezed the bill's name to "PG&E Ele…", so the row
# shows it only from @lg and the drawer carries it.
test "an estimated bill's range leaves the row on a phone and stays in the drawer" do
@@ -2323,6 +2411,25 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
assert_no_match I18n.t("bills.index.suggestion_line", entry: "SKIPPED GYM", bill: "SKIPPED GYM"), response.body
end
+ # Paid ahead, next month's bill lists in next month, so this month's queue
+ # mustn't ask about it either.
+ test "a suggestion against next month's bill paid early stays out of this month's review queue" do
+ travel_to Date.current.end_of_month
+ due = Date.current + 1
+ bill = declare_bill(name: "EARLY GYM", amount: 40, due: due)
+ occurrence = bill.recurring_occurrences.find_by!(due_on: due)
+ charge = create_transaction_entry(name: "EARLY GYM", amount: 40, date: Date.current)
+ RecurringTransaction::Allocator.new(occurrence).allocate_matched!(
+ entry: charge, state: "suggested", confidence: 0.7, signals: { name: 0.35 }
+ )
+ pay(occurrence)
+
+ get bills_url
+
+ assert_response :success
+ assert_no_match I18n.t("bills.index.suggestion_line", entry: "EARLY GYM", bill: "EARLY GYM"), response.body
+ end
+
# The overview groups by calendar month, which is the wrong unit for anyone
# paid weekly: four paychecks and four rent payments land in one list. The
@@ -2453,6 +2560,20 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
ApplicationController.helpers.format_money(Money.new(amount, @family.currency))
end
+ # A bill due six days ago, snoozed a week: the one snooze the app offers.
+ def snoozed_late_bill
+ late = 6.days.ago.to_date
+ bill = create_bill(name: "Late Co", amount: 30, expected_day_of_month: late.day,
+ last_occurrence_date: 2.months.ago.to_date, next_expected_date: late)
+ occurrence = bill.recurring_occurrences.open_status.order(:due_on).first
+ occurrence.snooze!(Date.current + 7)
+ occurrence
+ end
+
+ def pay(occurrence)
+ RecurringTransaction::Allocator.new(occurrence).mark_paid!(paid_on: Date.current)
+ end
+
def create_transaction_entry(name:, amount:, date:, account: accounts(:depository))
account.entries.create!(
date: date, amount: amount, currency: "USD", name: name,
diff --git a/test/models/assistant/function/get_paycheck_plan_test.rb b/test/models/assistant/function/get_paycheck_plan_test.rb
index bbeba99561..be0e2301dc 100644
--- a/test/models/assistant/function/get_paycheck_plan_test.rb
+++ b/test/models/assistant/function/get_paycheck_plan_test.rb
@@ -139,6 +139,20 @@ class Assistant::Function::GetPaycheckPlanTest < ActiveSupport::TestCase
assert_not bridge.key?(:cash_on_hand)
end
+ # The plan files a snoozed bill at the date it was snoozed to, so the
+ # assistant needs that date to explain where the bill sits. due_on stays the
+ # scheduled date, as in get_bills, because that is what pays it.
+ test "a snoozed bill reports the date it was snoozed to beside its due date" do
+ declare_future_income
+ haircut = declare_bridge_bill(amount: 150)
+ haircut.recurring_occurrences.first.snooze!(Date.current + 3)
+
+ bill = call_tool[:periods].flat_map { |period| period[:bills_due] }.sole
+
+ assert_equal (Date.current + 1).iso8601, bill[:due_on]
+ assert_equal (Date.current + 3).iso8601, bill[:effective_due_on]
+ end
+
private
# The shared declare_income pays today, so there is no gap before the next
diff --git a/test/models/recurring_transaction/paycheck_planner_test.rb b/test/models/recurring_transaction/paycheck_planner_test.rb
index faafc8bff2..9a394d93d1 100644
--- a/test/models/recurring_transaction/paycheck_planner_test.rb
+++ b/test/models/recurring_transaction/paycheck_planner_test.rb
@@ -328,6 +328,72 @@ class RecurringTransaction::PaycheckPlannerTest < ActiveSupport::TestCase
assert_includes plan.first.items, shares.first, "and it belongs to the leading window"
end
+ # Snoozing moves the day a bill falls due, and the overview's pay-period
+ # markers already file a snoozed bill under the paycheck its new date lands
+ # in. The plan kept the old date, so a bill snoozed past payday stayed owed
+ # before it and the cash in hand read as short.
+ test "a bill snoozed past payday is due in that payday's window" do
+ set_cash(100)
+ payday = Date.current + 3
+ create_series(name: "Paycheck", amount: -1840, due: payday, preset: "weekly", income: true)
+ create_series(name: "Internet", amount: 90, due: payday + 2)
+ power = create_series(name: "Power", amount: 120, due: Date.current - 6).recurring_occurrences.open_status.order(:due_on).first
+ water = create_series(name: "Water", amount: 120, due: Date.current + 1).recurring_occurrences.open_status.order(:due_on).first
+ power.snooze!(payday + 4)
+ water.snooze!(payday + 5)
+
+ plan = Planner.new(@family, user: @user).plan(periods_limit: 3)
+
+ assert_equal 0, plan.first.due_total, "nothing snoozed past payday is owed before it"
+ assert_not plan.first.short?, "so $100 in the bank is not short"
+ assert_equal %w[Internet Power Water], plan[1].items_due.map { |item| item.occurrence.recurring_transaction.name },
+ "payday's window carries both, in the order of the dates they were snoozed to"
+ markers = ApplicationController.helpers.bills_pay_period_markers([ power ], plan)
+ assert_equal plan[1], markers.dig(power.id, :period), "the overview marks it under the same paycheck"
+ end
+
+ # Bills claim paychecks in date order, so a window's own bills are funded
+ # before a later bill's overflow reaches back for the spare. A snoozed bill
+ # takes its turn at its new date, or its overflow empties the paycheck of a
+ # bill that now falls due before it.
+ test "a snoozed bill claims paychecks in the order of its new date" do
+ payday = Date.current + 3
+ create_series(name: "Paycheck", amount: -100, due: payday, preset: "weekly", income: true)
+ create_series(name: "Phone", amount: 150, due: payday + 8)
+ insurance = create_series(name: "Insurance", amount: 150, due: payday + 1)
+ insurance.recurring_occurrences.open_status.order(:due_on).first.snooze!(payday + 15)
+
+ plan = Planner.new(@family, user: @user).plan(periods_limit: 3)
+
+ assert_equal 100, plan[3].due_total, "premise: the insurance is due in the week it was snoozed to"
+ assert_equal 100, plan[2].due_total, "the phone bill takes its own paycheck before the insurance can"
+ assert_equal 0, plan[2].reserved_total
+ assert_equal %w[Phone Insurance], plan[1].items_reserved.map { |item| item.occurrence.recurring_transaction.name },
+ "the first paycheck holds both overflows, listed in the order they fall due"
+ end
+
+ # A snooze can carry a bill out of the plan altogether. It is no longer one
+ # of the plan's bills then, so it is in no period, and not among the bills
+ # the page says it could not convert either.
+ test "a bill snoozed past the last period leaves the plan" do
+ payday = Date.current + 3
+ create_series(name: "Paycheck", amount: -1840, due: payday, preset: "weekly", income: true)
+ bills = [
+ create_series(name: "Insurance", amount: 300, due: payday + 2),
+ create_series(name: "Tokyo storage", amount: 50_000, due: payday + 2, currency: "JPY")
+ ]
+ planner = Planner.new(@family, user: @user)
+ last_day = planner.plan(periods_limit: 2).last.ends_on
+ assert_equal 1, planner.unconvertible_count, "premise: inside the plan, the yen bill has no rate"
+
+ bills.each { |bill| bill.recurring_occurrences.open_status.order(:due_on).first.snooze!(last_day + 1) }
+ planner = Planner.new(@family, user: @user)
+ plan = planner.plan(periods_limit: 2)
+
+ assert plan.flat_map(&:items).none? { |item| bills.include?(item.occurrence.recurring_transaction) }
+ assert_equal 0, planner.unconvertible_count
+ end
+
# The bridge window earns nothing by construction, so judging it the way every
# other window is judged made "short before your next payday" fire for anyone
@@ -403,12 +469,12 @@ class RecurringTransaction::PaycheckPlannerTest < ActiveSupport::TestCase
@family.accounts.where(accountable_type: %q(Depository)).update_all(balance: amount / @family.accounts.where(accountable_type: %q(Depository)).count.to_d)
end
- def create_series(name:, amount:, due:, preset: "monthly", income: false)
+ def create_series(name:, amount:, due:, preset: "monthly", income: false, currency: "USD")
series = @family.recurring_transactions.create!(
name: name,
account: @account,
amount: amount,
- currency: "USD",
+ currency: currency,
bill_type: income ? "income" : "bill",
expected_day_of_month: due.day,
anchor_date: due,