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

95 lines
3.3 KiB
Ruby

class RecurringTransaction
# Materializes Schedule output into recurring_occurrences rows. An idempotent
# upsert keyed on (series, original_due_on), so re-running only adds missing
# rows and never duplicates or touches existing ones.
#
# Only scheduled, allocation-free, not-yet-due rows are ever deleted. Anything
# closed or carrying a payment is immutable history.
class OccurrenceGenerator
HORIZON_DAYS = 90
attr_reader :series
def initialize(series)
@series = series
end
# From the start of the current cycle, so a recently-due unpaid occurrence
# exists and not just future ones, through a horizon always extended far
# enough to include the next occurrence even on annual cadences.
def generate!(through: nil)
return 0 unless series.active?
schedule = series.schedule
from = schedule.cycle_for(Date.current)&.begin || Date.current
# A declared bill's anchor is its first obligation, so the cycle lookback
# must not fabricate a previous-cycle debt. Auto-detected series keep the
# cycle start, since their history predates the row.
from = [ from, series.anchor_date ].compact.max if series.manual?
through ||= default_horizon(schedule)
upsert_window(from, through)
end
# After a schedule edit: drop the re-generatable future and rebuild it under
# the new rules. Rows with payments or closed state are kept as they were.
def regenerate_future!(through: nil)
series.recurring_occurrences
.open_status
.where("due_on >= ?", Date.current)
.where.not(id: RecurringAllocation.select(:recurring_occurrence_id))
.delete_all
generate!(through: through)
end
# Materializes a past window (catch-up/backfill). The caller decides what
# happens to uncovered past occurrences; this only creates rows.
def backfill!(from:, through: Date.current)
return 0 unless series.active?
upsert_window(from, through)
end
private
def default_horizon(schedule)
horizon = Date.current + HORIZON_DAYS
next_due = schedule.first_occurrence_after(Date.current)
# A finite plan materializes whole: an installment run is bounded by
# definition, and seeing all N payments (and the end) is the point.
if series.ends_after_count? && series.end_after_count.present?
cycle_days = (365.25 / schedule.occurrences_per_year).ceil
plan_end = (series.anchor_date || Date.current) + cycle_days * (series.end_after_count + 1)
return [ horizon, next_due, plan_end ].compact.max
end
[ horizon, next_due ].compact.max
end
def upsert_window(from, through)
pairs = series.schedule.occurrence_pairs_between(from, through)
return 0 if pairs.empty?
now = Time.current
rows = pairs.map do |pair|
{
recurring_transaction_id: series.id,
family_id: series.family_id,
original_due_on: pair.original_due_on,
due_on: pair.due_on,
currency: series.currency,
status: "scheduled",
created_at: now,
updated_at: now
}
end
result = RecurringOccurrence.insert_all(rows, unique_by: "idx_recurring_occurrences_identity")
result.rows.size
end
end
end