Files
sure/app/models/recurrence_rule.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

51 lines
2.6 KiB
Ruby

# One repetition pattern of a recurring transaction. A series usually has one
# rule ("monthly on the 15th"); patterns that fire more than once per period are
# several rows ("semimonthly" is two monthly rules, "1st and 3rd Friday" is two
# nth-weekday rules). A series with zero rules is legal and means "legacy
# monthly on expected_day_of_month"; RecurringTransaction::Schedule synthesizes
# the implicit rule.
#
# Day anchoring is exactly one of:
# * day_of_month (1..31, or -1 for the last day of the month)
# * a (weekday, weekday_ordinal) pair ("3rd Friday"; ordinal -1 = last)
class RecurrenceRule < ApplicationRecord
LAST = -1
belongs_to :recurring_transaction
enum :frequency, { weekly: "weekly", monthly: "monthly", yearly: "yearly" }
validates :frequency, presence: true, inclusion: { in: frequencies.keys }
validates :interval, presence: true, numericality: { only_integer: true, greater_than: 0 }
validates :day_of_month, numericality: { only_integer: true, in: -1..31, other_than: 0 }, allow_nil: true
validates :weekday, numericality: { only_integer: true, in: 0..6 }, allow_nil: true
validates :weekday_ordinal, numericality: { only_integer: true, in: -1..5, other_than: 0 }, allow_nil: true
validates :month_of_year, numericality: { only_integer: true, in: 1..12 }, allow_nil: true
# Position uniqueness is left to the DB index: rules are rewritten as a set,
# so a model-level check would see the doomed rows and reject the rewrite.
validates :position, presence: true,
numericality: { only_integer: true, greater_than_or_equal_to: 0 }
validate :day_spec_coherent
private
def day_spec_coherent
case frequency
when "weekly"
errors.add(:weekday, :required_for_weekly) if weekday.blank?
errors.add(:weekday_ordinal, :not_allowed_for_weekly) if weekday_ordinal.present?
errors.add(:day_of_month, :not_allowed_for_weekly) if day_of_month.present?
errors.add(:month_of_year, :not_allowed) if month_of_year.present?
when "monthly", "yearly"
if frequency == "yearly"
errors.add(:month_of_year, :required_for_yearly) if month_of_year.blank?
else
errors.add(:month_of_year, :not_allowed) if month_of_year.present?
end
errors.add(:base, :day_spec_required) unless day_of_month.present? ^ weekday.present?
errors.add(:weekday_ordinal, :required_with_weekday) if weekday.present? && weekday_ordinal.blank?
errors.add(:weekday_ordinal, :not_allowed_without_weekday) if weekday_ordinal.present? && weekday.blank?
end
end
end