Files
sure/test/models/recurrence_rule_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

123 lines
4.3 KiB
Ruby

require "test_helper"
class RecurrenceRuleTest < ActiveSupport::TestCase
def setup
@recurring = recurring_transactions(:netflix_subscription)
end
test "monthly rule with a day of month is valid" do
rule = @recurring.recurrence_rules.build(frequency: "monthly", day_of_month: 15)
assert rule.valid?, rule.errors.full_messages.join(", ")
end
test "monthly rule accepts -1 as last day of month" do
rule = @recurring.recurrence_rules.build(frequency: "monthly", day_of_month: -1)
assert rule.valid?
end
test "monthly rule with an nth weekday is valid" do
rule = @recurring.recurrence_rules.build(frequency: "monthly", weekday: 5, weekday_ordinal: 3)
assert rule.valid?
end
test "monthly rule requires exactly one day spec" do
neither = @recurring.recurrence_rules.build(frequency: "monthly")
assert_not neither.valid?
both = @recurring.recurrence_rules.build(frequency: "monthly", day_of_month: 15, weekday: 5, weekday_ordinal: 3)
assert_not both.valid?
end
test "monthly weekday rule requires the ordinal" do
rule = @recurring.recurrence_rules.build(frequency: "monthly", weekday: 5)
assert_not rule.valid?
assert rule.errors[:weekday_ordinal].any?
end
test "weekly rule requires a weekday and rejects month-shaped fields" do
valid = @recurring.recurrence_rules.build(frequency: "weekly", weekday: 4)
assert valid.valid?
no_weekday = @recurring.recurrence_rules.build(frequency: "weekly")
assert_not no_weekday.valid?
with_day = @recurring.recurrence_rules.build(frequency: "weekly", weekday: 4, day_of_month: 10)
assert_not with_day.valid?
with_ordinal = @recurring.recurrence_rules.build(frequency: "weekly", weekday: 4, weekday_ordinal: 2)
assert_not with_ordinal.valid?
end
test "yearly rule requires a month and a day spec" do
valid = @recurring.recurrence_rules.build(frequency: "yearly", month_of_year: 11, day_of_month: 1)
assert valid.valid?
thanksgiving = @recurring.recurrence_rules.build(frequency: "yearly", month_of_year: 11, weekday: 4, weekday_ordinal: 4)
assert thanksgiving.valid?
no_month = @recurring.recurrence_rules.build(frequency: "yearly", day_of_month: 1)
assert_not no_month.valid?
end
test "monthly rule rejects month_of_year" do
rule = @recurring.recurrence_rules.build(frequency: "monthly", day_of_month: 5, month_of_year: 3)
assert_not rule.valid?
end
test "interval must be positive" do
rule = @recurring.recurrence_rules.build(frequency: "monthly", day_of_month: 5, interval: 0)
assert_not rule.valid?
end
test "position collisions are caught by the database index" do
# No model-level uniqueness validation on purpose: rules are rewritten as
# a set (old rows marked for destruction alongside new builds), and a
# validation would see the doomed rows and reject the rewrite.
@recurring.recurrence_rules.create!(frequency: "monthly", day_of_month: 1, position: 0)
assert_raises ActiveRecord::RecordNotUnique do
@recurring.recurrence_rules.create!(frequency: "monthly", day_of_month: 15, position: 0)
end
end
test "series with an interval rule requires an anchor date" do
@recurring.recurrence_rules.create!(frequency: "weekly", weekday: 5, interval: 2)
@recurring.anchor_date = nil
assert_not @recurring.valid?
assert @recurring.errors[:anchor_date].any?
@recurring.anchor_date = Date.new(2026, 8, 7)
assert @recurring.valid?
end
test "series end mode fields are validated together" do
@recurring.end_mode = "on_date"
assert_not @recurring.valid?
@recurring.end_on = Date.new(2027, 1, 1)
assert @recurring.valid?
@recurring.end_mode = "after_count"
@recurring.end_on = nil
assert_not @recurring.valid?
@recurring.end_after_count = 12
assert @recurring.valid?
end
test "rules are destroyed with their series" do
@recurring.recurrence_rules.create!(frequency: "monthly", day_of_month: 5)
assert_difference "RecurrenceRule.count", -1 do
@recurring.destroy!
end
end
test "a week-of-month anchor without a weekday is rejected" do
rule = @recurring.recurrence_rules.build(frequency: "monthly", day_of_month: 10, weekday_ordinal: 2)
assert_not rule.valid?
assert rule.errors[:weekday_ordinal].any?,
"an ordinal with no weekday persists an incoherent day anchor"
end
end