Files
sure/test/models/recurring_transaction/occurrence_generator_test.rb
T
Brandon 686205c0ff feat(bills): schema and domain core for the bills subsystem (#3201)
* feat(bills): schema and domain core for the bills subsystem

First of three chunks carved out of #3083. This one carries the schema and the
domain layer: no bills pages, no calendar feed, no assistant tools. Nothing here
is reachable from the UI yet, so it changes no user-visible behavior on its own.

Schema, in a single migration with a full down:

- recurrence_rules, recurring_occurrences, recurring_allocations,
  recurring_price_changes and recurring_match_rejections
- bill columns on recurring_transactions (bill_type, payment_url, autopay,
  notes, anchor and end conditions, weekend adjustment, dedup scope)
- the four data backfills, in their original order

Domain layer:

- Schedule, the pure date PORO every cadence resolves through, and
  FrequencyPreset for the labels
- OccurrenceGenerator, Matcher, Allocator, PriceChangeDetector, Classifier,
  DeclaredBill, HistoryBackfiller and PaycheckPlanner
- Pipeline, tying detection to generation, plus the nightly job and rake task

Existing detection code changed in three places, each a bug this schema exposes:

- Cleaner used a flat two-month staleness threshold, which silently retired
  every quarterly and annual series
- SubscriptionAuditGenerator used a flat 45-day overdue threshold, meaningless
  at both ends of the frequency range
- CashFlowWarningGenerator read one projected entry per series, which only
  equalled the monthly amount because every series was monthly; weekly bills
  were under-counted fourfold in its 30-day projection

The JSON API travels with the model rather than the UI, because the status enum
widens here. The API accepts only active and inactive on write; suggested,
paused and ended are lifecycle states owned by detection, so the documented
enum stays truthful.

Uniqueness keys gain dedup_scope alongside amount, never instead of it: a
series that is not price-forked carries a blank scope, so amount is what keeps
two different prices apart.

Suite 7,550 runs, 0 failures. Rubocop and brakeman clean. Eager loading
verified, and the migration reverses and re-applies. Includes the first review round: orphan repair matches income and refuses coincidental twins, session imports persist occurrence mappings across chunks, semimonthly anchors canonicalize, classifier keywords match whole words, and the down refuses rather than failing when price-forked rows exist.

* Address second review round

Bound the cross-currency default allocation by the entry leftover and the
occurrence remainder, matching the same-currency path. Let keyword stems
carry a suffix again after the word-boundary fix silenced them. Skip an
incoherent recurrence rule row instead of rolling back the whole import.
Check rollback collisions per restored index so a refusal cannot land
after the bills tables are dropped. Replay the closed_at test through a
real second import. Preload the orphan repair associations and move the
allocator errors to locale keys.

* Match index NULL semantics in the rollback collision checks

GROUP BY treats NULLs as equal but the restored unique indexes do not:
account_id is nullable and indexed, so two accountless rows can never
collide under any of them. Excluding NULL accounts keeps the guard from
refusing a rollback PostgreSQL can perform. Verified live both ways:
accountless duplicates roll back, a real collision still refuses.

* Address maintainer review

Scope the payable debt-destination subquery to the row and its family
instead of scanning every account in the installation. Batch the cash
flow generator remaining-amount sums into one grouped query, matching
the two sibling sites. Enforce both window bounds in the after_count
branch so a future-anchored plan cannot leak past the requested end
date. Skip the explicit regeneration when the day column change will
fire the model callback anyway. Add the missing locale entry for the
allocation currency validation.
2026-08-31 23:41:38 +02:00

103 lines
4.2 KiB
Ruby

require "test_helper"
class RecurringTransaction::OccurrenceGeneratorTest < ActiveSupport::TestCase
Generator = RecurringTransaction::OccurrenceGenerator
def setup
@family = families(:dylan_family)
@series = recurring_transactions(:netflix_subscription)
@series.recurring_occurrences.delete_all
end
test "generates the current cycle and the horizon idempotently" do
travel_to Date.new(2026, 8, 13) do
created = Generator.new(@series).generate!
occurrences = @series.recurring_occurrences.order(:due_on)
# Day-5 monthly bill: the current cycle started Aug 5, so the
# recently-due occurrence exists alongside the future window.
assert_equal Date.new(2026, 8, 5), occurrences.first.due_on
assert_operator occurrences.last.due_on, :<=, Date.new(2026, 11, 13)
assert_operator created, :>=, 3
assert_equal 0, Generator.new(@series).generate!, "second run inserts nothing"
end
end
test "the horizon always includes the next occurrence of a slow cadence" do
travel_to Date.new(2026, 8, 13) do
RecurringTransaction::FrequencyPreset.apply(@series, preset: "annual", day_of_month: "1", month_of_year: "3")
@series.save!
# insert_all bypasses the association layer, so read back fresh.
dues = @series.recurring_occurrences.reload.pluck(:due_on)
assert_includes dues, Date.new(2027, 3, 1), "annual occurrence beyond 90 days must still materialize"
end
end
test "regenerate_future! respects closed and allocated rows" do
travel_to Date.new(2026, 8, 13) do
Generator.new(@series).generate!
paid = @series.recurring_occurrences.find_by!(due_on: Date.new(2026, 9, 5))
paid.allocations.create!(allocated_amount: 5, currency: "USD", source: "user_created")
future = @series.recurring_occurrences.find_by!(due_on: Date.new(2026, 10, 5))
RecurringTransaction::FrequencyPreset.apply(@series, preset: "monthly", day_of_month: "20")
@series.save!
remaining = @series.recurring_occurrences.reload
assert_includes remaining.map(&:id), paid.id, "allocated rows survive schedule edits"
assert_not_includes remaining.map(&:id), future.id, "unallocated future rows are rebuilt"
assert_includes remaining.map(&:due_on), Date.new(2026, 8, 20)
end
end
test "pausing prunes the re-generatable future and resuming rebuilds it" do
travel_to Date.new(2026, 8, 13) do
Generator.new(@series).generate!
assert_operator @series.recurring_occurrences.count, :>, 1
@series.update!(status: "paused")
assert_equal 0, @series.recurring_occurrences.where("due_on >= ?", Date.current).count
@series.update!(status: "active")
assert_operator @series.recurring_occurrences.where("due_on >= ?", Date.current).count, :>=, 3
end
end
test "a declared bill's first obligation is its anchor, never a fabricated previous cycle" do
travel_to Date.new(2026, 8, 13) do
declared = @family.recurring_transactions.create!(
name: "Declared rent", amount: 2150, currency: "USD",
expected_day_of_month: 23, anchor_date: Date.new(2026, 8, 23),
last_occurrence_date: Date.new(2026, 8, 23), next_expected_date: Date.new(2026, 8, 23),
status: "active", manual: true
)
first = declared.recurring_occurrences.reload.order(:due_on).first
assert_equal Date.new(2026, 8, 23), first.due_on, "no phantom July 23 debt"
end
end
test "suggested series generate nothing" do
@series.update!(status: "suggested")
assert_equal 0, Generator.new(@series).generate!.to_i
assert_empty @series.recurring_occurrences
end
test "occurrence identity is the raw date, so weekend adjustment does not fork rows" do
travel_to Date.new(2026, 8, 1) do
RecurringTransaction::FrequencyPreset.apply(@series, preset: "monthly", day_of_month: "15")
@series.weekend_adjust = "before"
@series.save!
# Aug 15 2026 is a Saturday: due Friday the 14th, identity still the 15th.
occurrence = @series.recurring_occurrences.find_by!(original_due_on: Date.new(2026, 8, 15))
assert_equal Date.new(2026, 8, 14), occurrence.due_on
assert_equal 0, Generator.new(@series).generate!, "adjusted occurrence does not re-insert"
end
end
end