The personal finance app for everyone (by everyone)
Ruby
feat(bills): schema and domain core for the bills subsystem (#3201)
Brandon686205c0ff1a
diff --git a/app/controllers/api/v1/recurring_transactions_controller.rb b/app/controllers/api/v1/recurring_transactions_controller.rbindex 9e56464c9b..cc06b50cd5 100644--- a/app/controllers/api/v1/recurring_transactions_controller.rb+++ b/app/controllers/api/v1/recurring_transactions_controller.rb@@ -3,6 +3,11 @@class Api::V1::RecurringTransactionsController < Api::V1::BaseControllerinclude Pagy::Backend+ # The model knows more statuses (suggested, paused, ended), but those are+ # lifecycle states owned by detection and the web UI; the API writes only+ # the two it documents.+ WRITABLE_STATUSES = %w[active inactive].freeze+before_action :ensure_read_scope, only: %i[index show]before_action :ensure_write_scope, only: %i[create update destroy]before_action :set_readable_recurring_transaction, only: :show@@ -13,7 +18,7 @@ class Api::V1::RecurringTransactionsController < Api::V1::BaseController@per_page = safe_per_page_paramrecurring_transactions_query = read_recurring_transactions_scope- .includes(:account, :merchant)+ .includes(:account, :merchant, :recurrence_rules).order(status: :asc, next_expected_date: :asc)recurring_transactions_query = apply_filters(recurring_transactions_query)@@ -213,6 +218,7 @@ class Api::V1::RecurringTransactionsController < Api::V1::BaseControllerinput = recurring_transaction_inputrecurring_transaction.errors.add(:last_occurrence_date, :blank) if input[:last_occurrence_date].blank?recurring_transaction.errors.add(:next_expected_date, :blank) if input[:next_expected_date].blank?+ validate_status_write_param(recurring_transaction)enddef validate_update_write_params(recurring_transaction)@@ -220,6 +226,15 @@ class Api::V1::RecurringTransactionsController < Api::V1::BaseControllerif input.key?(:next_expected_date) && input[:next_expected_date].blank?recurring_transaction.errors.add(:next_expected_date, :blank)end+ validate_status_write_param(recurring_transaction)+ end++ # A blank status falls through to the model's presence validation.+ def validate_status_write_param(recurring_transaction)+ status = recurring_transaction_input[:status]+ return if status.blank? || status.to_s.in?(WRITABLE_STATUSES)++ recurring_transaction.errors.add(:status, :inclusion)enddef recurring_transaction_input@@ -246,7 +261,10 @@ class Api::V1::RecurringTransactionsController < Api::V1::BaseController:manual,:expected_amount_min,:expected_amount_max,- :expected_amount_avg+ :expected_amount_avg,+ :payment_url,+ :autopay,+ :notes)end@@ -254,7 +272,10 @@ class Api::V1::RecurringTransactionsController < Api::V1::BaseControllerparams.require(:recurring_transaction).permit(:status,:expected_day_of_month,- :next_expected_date+ :next_expected_date,+ :payment_url,+ :autopay,+ :notes)enddiff --git a/app/jobs/generate_recurring_occurrences_job.rb b/app/jobs/generate_recurring_occurrences_job.rbnew file mode 100644index 0000000000..cd91223125--- /dev/null+++ b/app/jobs/generate_recurring_occurrences_job.rb@@ -0,0 +1,39 @@+# Nightly sweep keeping every family's occurrence window materialized (the+# sync-triggered pipeline covers synced families; this catches manual-only+# families that never sync). Runs before GenerateInsightsJob so generators+# see fresh occurrences.+class GenerateRecurringOccurrencesJob < ApplicationJob+ queue_as :scheduled+ sidekiq_options lock: :until_executed, on_conflict: :log++ def perform(family_id = nil)+ if family_id.nil?+ fan_out+ else+ generate_for_family(family_id)+ end+ end++ private+ def fan_out+ Family.find_each do |family|+ next if family.recurring_transactions_disabled?++ self.class.perform_later(family.id)+ end+ end++ def generate_for_family(family_id)+ family = Family.find_by(id: family_id)+ return unless family+ return if family.recurring_transactions_disabled?++ # Shares the pipeline's per-family lock so the nightly sweep and the+ # sync-triggered pipeline serialize against each other.+ RecurringTransaction::Pipeline.with_family_lock(family_id) do+ family.recurring_transactions.active.find_each do |series|+ RecurringTransaction::OccurrenceGenerator.new(series).generate!+ end+ end+ end+enddiff --git a/app/jobs/identify_recurring_transactions_job.rb b/app/jobs/identify_recurring_transactions_job.rbindex d6ca2dffac..61d2117268 100644--- a/app/jobs/identify_recurring_transactions_job.rb+++ b/app/jobs/identify_recurring_transactions_job.rb@@ -1,3 +1,5 @@+# Bills subsystem: after detecting patterns this now runs the rest of the+# pipeline -- materialize occurrences, repair provider-replaced entries, match.class IdentifyRecurringTransactionsJob < ApplicationJobqueue_as :default@@ -18,8 +20,8 @@ class IdentifyRecurringTransactionsJob < ApplicationJobreturn if family_has_incomplete_syncs?(family)# Use advisory lock as final safety net against concurrent execution- with_advisory_lock(family_id) do- RecurringTransaction::Identifier.new(family).identify_recurring_patterns+ RecurringTransaction::Pipeline.with_family_lock(family_id) do+ RecurringTransaction::Pipeline.new(family).run!endend@@ -50,27 +52,4 @@ class IdentifyRecurringTransactionsJob < ApplicationJobdef family_has_incomplete_syncs?(family)Sync.any_incomplete_for?(family)end-- def with_advisory_lock(family_id)- lock_key = advisory_lock_key(family_id)- acquired = ActiveRecord::Base.connection.select_value(- ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_try_advisory_lock(?)", lock_key ])- )-- return unless acquired-- begin- yield- ensure- ActiveRecord::Base.connection.execute(- ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_advisory_unlock(?)", lock_key ])- )- end- end-- def advisory_lock_key(family_id)- # Generate a stable integer key from the family ID for PostgreSQL advisory lock- # Advisory locks require a bigint key- Digest::MD5.hexdigest("recurring_transaction_identify:#{family_id}").to_i(16) % (2**31)- endenddiff --git a/app/models/budget_category.rb b/app/models/budget_category.rbindex 790273be04..f4375ad29f 100644--- a/app/models/budget_category.rb+++ b/app/models/budget_category.rb@@ -1,4 +1,21 @@+# Bills subsystem: exposes what this category's bills have already committed+# inside the budget period, as a read-side hook only.class BudgetCategory < ApplicationRecord+ # Money this category's bills still expect inside the budget period --+ # committed but not yet spent. Read-side only: budgets stay derived from+ # posted entries, and debt-payment transfers never reach here because+ # transfer series carry no category.+ def bills_reserved+ bills_reservation.first+ end++ # Obligations in this period with no rate into the budget currency. Counted+ # and reported rather than dropped: a reservation that silently omits money+ # reads as money the user still has free to spend.+ def bills_reserved_unconvertible_count+ bills_reservation.last+ end+include Monetizablebelongs_to :budget@@ -400,6 +417,50 @@ class BudgetCategory < ApplicationRecordendprivate+ # A foreign-currency obligation is converted, not skipped: it is still owed+ # out of this category. Only one with no rate at all falls out, and that one+ # is counted.+ def bills_reservation+ @bills_reservation ||= begin+ occurrences = RecurringOccurrence+ .open_status+ .joins(:recurring_transaction)+ .where(recurring_transactions: {+ family_id: budget.family_id,+ category_id: category_id,+ status: :active,+ destination_account_id: nil+ })+ .where("recurring_transactions.amount > 0")+ .where(due_on: budget.start_date..budget.end_date)+ .includes(:recurring_transaction)+ .to_a++ # One grouped sum for the whole set. Reading remaining_amount straight+ # off each row issues a SUM per occurrence, which is a query count that+ # grows with the number of bills the user has.+ sums = RecurringAllocation.confirmed+ .where(recurring_occurrence_id: occurrences.map(&:id))+ .group(:recurring_occurrence_id)+ .sum(:allocated_amount)++ unconvertible = 0++ total = occurrences.reduce(Money.new(0, currency)) do |sum, occurrence|+ occurrence.cached_confirmed_allocated = sums.fetch(occurrence.id, 0)++ begin+ sum + occurrence.remaining_amount_money.exchange_to(currency)+ rescue Money::ConversionError+ unconvertible += 1+ sum+ end+ end++ [ total, unconvertible ]+ end+ end+def sync_parent_budgeted_spending!(previous_budgeted_spending:)parent_budget_category = budget.budget_categories.where(category_id: category.parent_id).lock.firstreturn unless parent_budget_categorydiff --git a/app/models/entry.rb b/app/models/entry.rbindex 3285b8d516..3d1fee3902 100644--- a/app/models/entry.rb+++ b/app/models/entry.rb@@ -19,6 +19,9 @@ class Entry < ApplicationRecordvalidates :reconciled_at, presence: true, if: -> { reconciled_by_statement_id.present? }has_many :child_entries, class_name: "Entry", foreign_key: :parent_entry_id, dependent: :destroy+ # Read side only, so a transaction can say which bills it paid. The foreign key+ # already nullifies on delete, so this adds no lifecycle behaviour.+ has_many :recurring_allocations, dependent: nil, inverse_of: :entrydelegated_type :entryable, types: Entryable::TYPES, dependent: :destroyaccepts_nested_attributes_for :entryablediff --git a/app/models/family.rb b/app/models/family.rbindex da3dbf3de1..387dd3effc 100644--- a/app/models/family.rb+++ b/app/models/family.rb@@ -116,6 +116,7 @@ class Family < ApplicationRecordhas_many :llm_usages, dependent: :destroyhas_many :recurring_transactions, dependent: :destroy+ has_many :recurring_occurrences, dependent: :destroyhas_many :insights, dependent: :destroy# Families with at least one opted-in member. Lets a job filter in onediff --git a/app/models/family/data_exporter.rb b/app/models/family/data_exporter.rbindex fbd6968d3f..cb514061c8 100644--- a/app/models/family/data_exporter.rb+++ b/app/models/family/data_exporter.rb@@ -320,6 +320,52 @@ class Family::DataExporter}.to_jsonend+ # The Bills subsystem hangs off those series. Rules and occurrences need+ # only the series; allocations, price changes and rejections also point+ # at transactions, so the importer replays them after transactions land.+ RecurrenceRule.joins(:recurring_transaction)+ .where(recurring_transactions: { family_id: @family.id })+ .find_each do |rule|+ lines << { type: "RecurrenceRule", data: serialize_recurrence_rule_for_export(rule) }.to_json+ end++ @family.recurring_occurrences.find_each do |occurrence|+ lines << {+ type: "RecurringOccurrence",+ data: serialize_recurring_occurrence_for_export(occurrence)+ }.to_json+ end++ RecurringAllocation.joins(:recurring_occurrence)+ .where(recurring_occurrences: { family_id: @family.id })+ .includes(:entry)+ .find_each do |allocation|+ lines << {+ type: "RecurringAllocation",+ data: serialize_recurring_allocation_for_export(allocation)+ }.to_json+ end++ RecurringPriceChange.joins(:recurring_transaction)+ .where(recurring_transactions: { family_id: @family.id })+ .includes(:entry)+ .find_each do |change|+ lines << {+ type: "RecurringPriceChange",+ data: serialize_recurring_price_change_for_export(change)+ }.to_json+ end++ RecurringMatchRejection.joins(:recurring_transaction)+ .where(recurring_transactions: { family_id: @family.id })+ .includes(:entry)+ .find_each do |rejection|+ lines << {+ type: "RecurringMatchRejection",+ data: serialize_recurring_match_rejection_for_export(rejection)+ }.to_json+ end+ndjson_exportable_transactions.includes(:category,:merchant,@@ -555,14 +601,120 @@ class Family::DataExporteroccurrence_count: recurring_transaction.occurrence_count,name: recurring_transaction.name,manual: recurring_transaction.manual,+ payment_url: recurring_transaction.payment_url,+ autopay: recurring_transaction.autopay,+ notes: recurring_transaction.notes,expected_amount_min: recurring_transaction.expected_amount_min,expected_amount_max: recurring_transaction.expected_amount_max,expected_amount_avg: recurring_transaction.expected_amount_avg,+ # Bills subsystem. Without these a restored bill keeps its name and+ # amount but loses what kind of obligation it is, what it costs to+ # match, and every schedule detail beyond the day of the month.+ bill_type: recurring_transaction.bill_type,+ category_id: recurring_transaction.category_id,+ amount_strategy: recurring_transaction.amount_strategy,+ amount_tolerance_pct: recurring_transaction.amount_tolerance_pct,+ notify_days_before: recurring_transaction.notify_days_before,+ upcoming_window_days: recurring_transaction.upcoming_window_days,+ overdue_grace_days: recurring_transaction.overdue_grace_days,+ match_days_early: recurring_transaction.match_days_early,+ match_days_late: recurring_transaction.match_days_late,+ renews_on: recurring_transaction.renews_on,+ trial_ends_on: recurring_transaction.trial_ends_on,+ cancelled_on: recurring_transaction.cancelled_on,+ anchor_date: recurring_transaction.anchor_date,+ end_mode: recurring_transaction.end_mode,+ end_on: recurring_transaction.end_on,+ end_after_count: recurring_transaction.end_after_count,+ weekend_adjust: recurring_transaction.weekend_adjust,+ holiday_calendar: recurring_transaction.holiday_calendar,+ matcher_hints: recurring_transaction.matcher_hints,+ dedup_scope: recurring_transaction.dedup_scope,+ replaced_by_id: recurring_transaction.replaced_by_id,created_at: recurring_transaction.created_at,updated_at: recurring_transaction.updated_at}end+ def serialize_recurrence_rule_for_export(rule)+ {+ id: rule.id,+ recurring_transaction_id: rule.recurring_transaction_id,+ frequency: rule.frequency,+ interval: rule.interval,+ day_of_month: rule.day_of_month,+ weekday: rule.weekday,+ weekday_ordinal: rule.weekday_ordinal,+ month_of_year: rule.month_of_year,+ position: rule.position+ }+ end++ def serialize_recurring_occurrence_for_export(occurrence)+ {+ id: occurrence.id,+ recurring_transaction_id: occurrence.recurring_transaction_id,+ original_due_on: occurrence.original_due_on,+ due_on: occurrence.due_on,+ currency: occurrence.currency,+ expected_amount: occurrence.expected_amount,+ status: occurrence.status,+ snoozed_until: occurrence.snoozed_until,+ closed_at: occurrence.closed_at,+ closed_source: occurrence.closed_source,+ notes: occurrence.notes+ }+ end++ # Allocations point at an Entry, but the importer only carries a+ # Transaction id map, so the link travels as the transaction that owns the+ # entry. An allocation whose entry cannot be resolved still imports: its+ # amount is the payment record, and a null entry is a shape the model+ # supports by design.+ def serialize_recurring_allocation_for_export(allocation)+ entry = allocation.entry++ {+ id: allocation.id,+ recurring_occurrence_id: allocation.recurring_occurrence_id,+ transaction_id: entry&.entryable_type == "Transaction" ? entry.entryable_id : nil,+ allocated_amount: allocation.allocated_amount,+ currency: allocation.currency,+ source_amount: allocation.source_amount,+ source_currency: allocation.source_currency,+ state: allocation.state,+ source: allocation.source,+ match_confidence: allocation.match_confidence,+ match_signals: allocation.match_signals,+ paid_on: allocation.paid_on+ }+ end++ def serialize_recurring_price_change_for_export(change)+ entry = change.entry++ {+ id: change.id,+ recurring_transaction_id: change.recurring_transaction_id,+ effective_on: change.effective_on,+ previous_amount: change.previous_amount,+ new_amount: change.new_amount,+ currency: change.currency,+ source: change.source,+ transaction_id: entry&.entryable_type == "Transaction" ? entry.entryable_id : nil+ }+ end++ def serialize_recurring_match_rejection_for_export(rejection)+ entry = rejection.entry++ {+ id: rejection.id,+ recurring_transaction_id: rejection.recurring_transaction_id,+ transaction_id: entry&.entryable_type == "Transaction" ? entry.entryable_id : nil+ }+ end+def serialize_rule_for_export(rule){id: rule.id,diff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rbindex 9f953a4aee..68188812e5 100644--- a/app/models/family/data_importer.rb+++ b/app/models/family/data_importer.rb@@ -31,7 +31,7 @@ class Family::DataImporterendend- SUPPORTED_TYPES = %w[Account Balance Category Tag Merchant RecurringTransaction Transaction Transfer RejectedTransfer Trade Holding Valuation Budget BudgetCategory Rule].freeze+ SUPPORTED_TYPES = %w[Account Balance Category Tag Merchant RecurringTransaction RecurrenceRule RecurringOccurrence RecurringAllocation RecurringPriceChange RecurringMatchRejection Transaction Transfer RejectedTransfer Trade Holding Valuation Budget BudgetCategory Rule].freezeACCOUNTABLE_TYPE_CLASSES = {"Depository" => Depository, "Investment" => Investment, "Crypto" => Crypto,"Property" => Property, "Vehicle" => Vehicle, "OtherAsset" => OtherAsset,@@ -48,6 +48,7 @@ class Family::DataImportertags: "Tag",merchants: "Merchant",recurring_transactions: "RecurringTransaction",+ recurring_occurrences: "RecurringOccurrence",transactions: "Transaction",budgets: "Budget",securities: "Security",@@ -60,6 +61,11 @@ class Family::DataImporter"Tag" => "tags","Merchant" => "merchants","RecurringTransaction" => "recurring_transactions",+ "RecurrenceRule" => "recurrence_rules",+ "RecurringOccurrence" => "recurring_occurrences",+ "RecurringAllocation" => "recurring_allocations",+ "RecurringPriceChange" => "recurring_price_changes",+ "RecurringMatchRejection" => "recurring_match_rejections","Transaction" => "transactions","Transfer" => "transfers","RejectedTransfer" => "rejected_transfers",@@ -83,12 +89,14 @@ class Family::DataImportertags: {},merchants: {},recurring_transactions: {},+ recurring_occurrences: {},transactions: {},budgets: {},securities: {},rules: {}}@security_cache = {}+ @pending_replacements = {}@created_accounts = []@created_entries = []@summary = Hash.new { |hash, key| hash[key] = empty_summary_bucket }@@ -108,6 +116,13 @@ class Family::DataImporterimport_merchants(records["Merchant"] || [])import_recurring_transactions(records["RecurringTransaction"] || [])import_transactions(records["Transaction"] || [])+ # Bills: rules and occurrences need their series, allocations and the+ # rest also need transactions, so all of it replays here.+ import_recurrence_rules(records["RecurrenceRule"] || [])+ import_recurring_occurrences(records["RecurringOccurrence"] || [])+ import_recurring_allocations(records["RecurringAllocation"] || [])+ import_recurring_price_changes(records["RecurringPriceChange"] || [])+ import_recurring_match_rejections(records["RecurringMatchRejection"] || [])import_transfers(records["Transfer"] || [])import_rejected_transfers(records["RejectedTransfer"] || [])import_trades(records["Trade"] || [])@@ -515,15 +530,70 @@ class Family::DataImporteroccurrence_count: data["occurrence_count"].to_i,name: data["name"],manual: boolean_import_value(data, "manual", default: false),+ payment_url: data["payment_url"],+ autopay: boolean_import_value(data, "autopay", default: false),+ notes: data["notes"],expected_amount_min: data["expected_amount_min"]&.to_d,expected_amount_max: data["expected_amount_max"]&.to_d,- expected_amount_avg: data["expected_amount_avg"]&.to_d+ expected_amount_avg: data["expected_amount_avg"]&.to_d,+ bill_type: imported_bill_type(data["bill_type"]),+ category_id: remap_optional_id(:categories, data["category_id"], record_type: "RecurringTransaction"),+ amount_strategy: imported_enum_value(data["amount_strategy"], RecurringTransaction.amount_strategies, "fixed"),+ notify_days_before: data["notify_days_before"],+ upcoming_window_days: data["upcoming_window_days"],+ overdue_grace_days: data["overdue_grace_days"],+ renews_on: parse_import_date(data["renews_on"]),+ trial_ends_on: parse_import_date(data["trial_ends_on"]),+ cancelled_on: parse_import_date(data["cancelled_on"]),+ anchor_date: parse_import_date(data["anchor_date"]),+ end_mode: imported_enum_value(data["end_mode"], RecurringTransaction.end_modes, "never"),+ end_on: parse_import_date(data["end_on"]),+ end_after_count: data["end_after_count"],+ weekend_adjust: imported_enum_value(data["weekend_adjust"], RecurringTransaction.weekend_adjusts, "none"),+ holiday_calendar: data["holiday_calendar"],+ matcher_hints: data["matcher_hints"] || {}+ )+ # These columns are NOT NULL with database defaults. An export written+ # before they existed omits them, and assigning nil would replace a+ # good default with a constraint violation, so they are only applied+ # when the export actually carries a value.+ recurring_transaction.assign_attributes(+ {+ amount_tolerance_pct: data["amount_tolerance_pct"]&.to_d,+ match_days_early: data["match_days_early"],+ match_days_late: data["match_days_late"],+ dedup_scope: data["dedup_scope"]+ }.compact)recurring_transaction.save!map_source!(:recurring_transactions, old_id, recurring_transaction)+ # A replacement points at another series that may not exist yet, so it+ # is resolved once every series has landed.+ @pending_replacements[old_id] = data["replaced_by_id"] if data["replaced_by_id"].present?increment_summary("RecurringTransaction", created ? :created : :updated)end++ resolve_pending_replacements!+ end++ def resolve_pending_replacements!+ @pending_replacements.each do |source_id, source_replacement_id|+ series_id = mapped_id(:recurring_transactions, source_id, record_type: "RecurringTransaction", required: false)+ replacement_id = mapped_id(:recurring_transactions, source_replacement_id, record_type: "RecurringTransaction", required: false)+ next if series_id.blank? || replacement_id.blank?++ @family.recurring_transactions.where(id: series_id).update_all(replaced_by_id: replacement_id)+ end+ @pending_replacements.clear+ end++ def imported_bill_type(value)+ imported_enum_value(value, RecurringTransaction.bill_types, "bill")+ end++ def imported_enum_value(value, allowed, fallback)+ value.to_s.in?(allowed.keys) ? value.to_s : fallbackenddef remap_optional_id(mapping_key, old_id, record_type:)@@ -532,6 +602,226 @@ class Family::DataImportermapped_id(mapping_key, old_id, record_type: record_type)end+ # --- Bills subsystem -------------------------------------------------+ #+ # Creating a series generates its own occurrences, so each of these matches+ # on natural identity rather than inserting blindly: the same export+ # replayed twice lands on the same rows.++ def import_recurrence_rules(records)+ records.each do |record|+ data = record["data"]+ series = imported_series_for(data, "RecurrenceRule")+ next if series.blank?++ rule = series.recurrence_rules.find_or_initialize_by(position: data["position"].to_i)+ created = rule.new_record?+ rule.assign_attributes(+ # Enum writers raise on unknown values, and one stale export value+ # must not abort the whole import.+ frequency: imported_enum_value(data["frequency"], RecurrenceRule.frequencies, "monthly"),+ interval: data["interval"].to_i,+ day_of_month: data["day_of_month"],+ weekday: data["weekday"],+ weekday_ordinal: data["weekday_ordinal"],+ month_of_year: data["month_of_year"]+ )+ rule.save!+ increment_summary("RecurrenceRule", created ? :created : :updated)+ rescue ActiveRecord::RecordInvalid+ # The enum fallback keeps unknown cadences from raising, but the+ # substituted monthly can still be incoherent with the row's other day+ # fields, and a missing interval reads as zero. One stale export row is+ # a skip, never a rollback of every record type in the file.+ increment_summary("RecurrenceRule", :skipped)+ end+ end++ def import_recurring_occurrences(records)+ records.each do |record|+ data = record["data"]+ series = imported_series_for(data, "RecurringOccurrence")+ next if series.blank?++ original_due_on = parse_import_date(data["original_due_on"])+ if original_due_on.blank?+ increment_summary("RecurringOccurrence", :skipped)+ next+ end++ occurrence = series.recurring_occurrences.find_or_initialize_by(original_due_on: original_due_on)+ created = occurrence.new_record?+ occurrence.assign_attributes(+ family: @family,+ due_on: parse_import_date(data["due_on"]) || original_due_on,+ currency: data["currency"] || series.currency,+ expected_amount: data["expected_amount"]&.to_d,+ status: imported_occurrence_status(data["status"]),+ snoozed_until: parse_import_date(data["snoozed_until"]),+ closed_at: data["closed_at"].presence && Time.zone.parse(data["closed_at"].to_s),+ # A check constraint limits closed_source; an unknown export value+ # degrades to nil rather than aborting the import.+ closed_source: data["closed_source"].to_s.presence_in(%w[auto user]),+ notes: data["notes"]+ )+ # A check constraint ties status and closed_at together, so a closed row+ # exported without a timestamp would otherwise fail the insert. The+ # stand-in derives from the due date, not the import time, so replaying+ # the same export lands on the same value.+ if occurrence.status == "scheduled"+ occurrence.closed_at = nil+ else+ occurrence.closed_at ||= occurrence.due_on.in_time_zone+ end++ occurrence.save!+ map_source!(:recurring_occurrences, data["id"], occurrence)+ increment_summary("RecurringOccurrence", created ? :created : :updated)+ end+ end++ def import_recurring_allocations(records)+ records.each do |record|+ data = record["data"]+ # Session imports arrive in chunks, each through a fresh importer. An+ # in-memory map died with its chunk, so an allocation landing after its+ # occurrence's chunk was silently skipped. The persisted mapping is the+ # one source that survives.+ occurrence_id = mapped_id(:recurring_occurrences, data["recurring_occurrence_id"],+ record_type: "RecurringAllocation", required: false)+ occurrence = RecurringOccurrence.find_by(id: occurrence_id) if occurrence_id.present?+ if occurrence.blank?+ increment_summary("RecurringAllocation", :skipped)+ next+ end++ entry_id = imported_entry_id(data["transaction_id"], "RecurringAllocation")+ paid_on = parse_import_date(data["paid_on"])+ amount = data["allocated_amount"].to_d++ # A hand-recorded payment is matched on its values, and paid_on is one+ # of them; without it the default (today) would make a replay on a+ # later day miss the row and insert a duplicate.+ if entry_id.blank? && paid_on.blank?+ invalid_record!("RecurringAllocation", "paid_on", data["paid_on"])+ next+ end++ allocation = if entry_id+ RecurringAllocation.find_or_initialize_by(+ recurring_occurrence_id: occurrence_id, entry_id: entry_id+ )+ else+ # A hand-recorded payment has no natural key, so it is matched on the+ # values that make it the same payment.+ RecurringAllocation.find_or_initialize_by(+ recurring_occurrence_id: occurrence_id, entry_id: nil,+ allocated_amount: amount, paid_on: paid_on+ )+ end++ created = allocation.new_record?+ allocation.assign_attributes(+ allocated_amount: amount,+ currency: occurrence.currency,+ source_amount: data["source_amount"]&.to_d,+ source_currency: data["source_currency"],+ state: imported_allocation_value(data["state"], RecurringAllocation.states, "confirmed"),+ source: imported_allocation_value(data["source"], RecurringAllocation.sources, "user_created"),+ match_confidence: data["match_confidence"]&.to_d,+ match_signals: data["match_signals"] || {},+ paid_on: paid_on+ )+ allocation.save!+ increment_summary("RecurringAllocation", created ? :created : :updated)+ end+ end++ def import_recurring_price_changes(records)+ records.each do |record|+ data = record["data"]+ series = imported_series_for(data, "RecurringPriceChange")+ next if series.blank?++ effective_on = parse_import_date(data["effective_on"])+ if effective_on.blank?+ increment_summary("RecurringPriceChange", :skipped)+ next+ end++ change = RecurringPriceChange.find_or_initialize_by(+ recurring_transaction_id: series.id, effective_on: effective_on+ )+ created = change.new_record?+ change.assign_attributes(+ previous_amount: data["previous_amount"].to_d,+ new_amount: data["new_amount"].to_d,+ currency: data["currency"] || series.currency,+ source: imported_enum_value(data["source"], RecurringPriceChange.sources, "detected"),+ entry_id: imported_entry_id(data["transaction_id"], "RecurringPriceChange")+ )+ change.save!+ increment_summary("RecurringPriceChange", created ? :created : :updated)+ end+ end++ def import_recurring_match_rejections(records)+ records.each do |record|+ data = record["data"]+ series = imported_series_for(data, "RecurringMatchRejection")+ next if series.blank?++ entry_id = imported_entry_id(data["transaction_id"], "RecurringMatchRejection")+ # entry_id is NOT NULL here, so a rejection whose transaction did not+ # come across cannot be represented and is dropped rather than faked.+ if entry_id.blank?+ increment_summary("RecurringMatchRejection", :skipped)+ next+ end++ rejection = RecurringMatchRejection.find_or_initialize_by(+ recurring_transaction_id: series.id, entry_id: entry_id+ )+ created = rejection.new_record?+ rejection.save!+ increment_summary("RecurringMatchRejection", created ? :created : :updated)+ end+ end++ # Counts the dropped record as skipped on every nil return, so a non-strict+ # import cannot silently discard rows whose series never came across.+ def imported_series_for(data, record_type)+ series_id = remap_optional_id(+ :recurring_transactions, data["recurring_transaction_id"], record_type: record_type+ )+ series = @family.recurring_transactions.find_by(id: series_id) if series_id.present?+ increment_summary(record_type, :skipped) if series.nil?+ series+ end++ # Allocations travel with the transaction that owns their entry, because+ # that is the only id map the importer carries. An unresolvable one leaves+ # the link null: the payment and its amount still survive, which is the+ # shape the model already supports for hand-recorded payments.+ def imported_entry_id(source_transaction_id, record_type)+ return if source_transaction_id.blank?++ new_transaction_id = mapped_id(+ :transactions, source_transaction_id, record_type: record_type, required: false+ )+ return if new_transaction_id.blank?++ Entry.find_by(entryable_type: "Transaction", entryable_id: new_transaction_id)&.id+ end++ def imported_occurrence_status(status)+ status.to_s.in?(RecurringOccurrence.statuses.keys) ? status.to_s : "scheduled"+ end++ def imported_allocation_value(value, allowed, fallback)+ value.to_s.in?(allowed.keys) ? value.to_s : fallback+ end+def recurring_transaction_status_for(status)status.to_s.in?(RecurringTransaction.statuses.keys) ? status.to_s : "active"enddiff --git a/app/models/import_source_mapping.rb b/app/models/import_source_mapping.rbindex c59bd8a818..7b174fb37a 100644--- a/app/models/import_source_mapping.rb+++ b/app/models/import_source_mapping.rb@@ -1,5 +1,5 @@class ImportSourceMapping < ApplicationRecord- SOURCE_TYPES = %w[Account Category Tag Merchant RecurringTransaction Transaction Budget Security Rule].freeze+ SOURCE_TYPES = %w[Account Category Tag Merchant RecurringTransaction RecurringOccurrence Transaction Budget Security Rule].freezebelongs_to :familybelongs_to :import_sessiondiff --git a/app/models/insight/generators/cash_flow_warning_generator.rb b/app/models/insight/generators/cash_flow_warning_generator.rbindex ad1bcdc8a2..5c2c7ff064 100644--- a/app/models/insight/generators/cash_flow_warning_generator.rb+++ b/app/models/insight/generators/cash_flow_warning_generator.rb@@ -1,6 +1,9 @@# Projects the family's combined cash (Depository) balance forward 30 days by# layering known recurring transactions on top of a statistical daily-spend# baseline, and warns when the projected balance dips below the threshold.+# Bills subsystem: projects from materialized occurrences rather than one+# projected entry per series, so non-monthly bills are counted at their real+# frequency and partial payments shrink the projection.class Insight::Generators::CashFlowWarningGenerator < Insight::Generatorproduces "cash_flow_warning"@@ -89,11 +92,32 @@ class Insight::Generators::CashFlowWarningGenerator < Insight::Generator# (IdentifyRecurringTransactionsJob) — it doesn't clear out ones already# identified, so this keeps using that last-known set rather than silently# degrading to the flatter median-only baseline.+ Obligation = Data.define(:date, :amount)++ # Occurrence rows instead of one projected entry per series: a weekly+ # bill contributes every hit inside the horizon (the single-projection+ # version silently under-counted it fourfold), and partially paid+ # occurrences contribute only what actually remains.def upcoming_recurring_entries- family.recurring_transactions- .expected_soon- .where(destination_account_id: nil)- .filter_map(&:projected_entry)- .select { |e| e.currency == family.currency && e.date <= Date.current + HORIZON_DAYS }+ occurrences = family.recurring_occurrences+ .open_status+ .joins(:recurring_transaction)+ .where(recurring_transactions: { status: :active, destination_account_id: nil })+ .where("recurring_transactions.amount > 0")+ .where(currency: family.currency)+ .where(due_on: Date.current..(Date.current + HORIZON_DAYS))+ .includes(:recurring_transaction)+ .to_a++ # remaining_amount reads the confirmed-allocation sum, and this runs+ # nightly for every family: one grouped query instead of one SUM per+ # occurrence in the horizon.+ sums = RecurringAllocation.confirmed+ .where(recurring_occurrence_id: occurrences.map(&:id))+ .group(:recurring_occurrence_id)+ .sum(:allocated_amount)+ occurrences.each { |occurrence| occurrence.cached_confirmed_allocated = sums.fetch(occurrence.id, 0) }++ occurrences.map { |occurrence| Obligation.new(date: occurrence.due_on, amount: occurrence.remaining_amount) }endenddiff --git a/app/models/insight/generators/subscription_audit_generator.rb b/app/models/insight/generators/subscription_audit_generator.rbindex 3a3d00708a..d29c2c507c 100644--- a/app/models/insight/generators/subscription_audit_generator.rb+++ b/app/models/insight/generators/subscription_audit_generator.rb@@ -1,6 +1,8 @@# Surfaces recurring expenses that are well past their expected date — the# provider may have raised the price, the charge may have moved, or the user# may be paying for something that quietly stopped (or should stop).+# Bills subsystem: the overdue threshold is now measured in the series' own+# cycles, so quarterly and annual bills are no longer judged by a flat 45 days.class Insight::Generators::SubscriptionAuditGenerator < Insight::Generatorproduces "subscription_audit"@@ -10,10 +12,11 @@ class Insight::Generators::SubscriptionAuditGenerator < Insight::Generatordef generatereturn [] if family.recurring_transactions_disabled?- overdue_recurring.map do |recurring|+ overdue_occurrences.map do |occurrence|+ recurring = occurrence.recurring_transactionname = recurring.merchant&.name.presence || recurring.name- amount = Money.new(recurring.amount, recurring.currency).format- days_overdue = (Date.current - recurring.next_expected_date).to_i+ amount = Money.new(occurrence.resolved_expected_amount, occurrence.currency).format+ days_overdue = (Date.current - occurrence.due_on).to_ibuild_insight(insight_type: "subscription_audit",@@ -24,14 +27,14 @@ class Insight::Generators::SubscriptionAuditGenerator < Insight::Generatorname: name,amount: amount,days_overdue: days_overdue,- expected_on: I18n.l(recurring.next_expected_date)+ expected_on: I18n.l(occurrence.due_on)},# days_overdue is deliberately left out: it changes every night, and# metadata drift would resurrect insights the user already dismissed.metadata: {recurring_transaction_id: recurring.id,- amount: round(recurring.amount, 2),- expected_on: recurring.next_expected_date.iso8601+ amount: round(occurrence.resolved_expected_amount, 2),+ expected_on: occurrence.due_on.iso8601},dedup_key: "subscription_audit:#{recurring.id}")@@ -39,14 +42,31 @@ class Insight::Generators::SubscriptionAuditGenerator < Insight::Generatorendprivate- def overdue_recurring- family.recurring_transactions- .includes(:merchant)- .active- .where(destination_account_id: nil)- .where("amount > 0")- .where("next_expected_date < ?", OVERDUE_DAYS.days.ago.to_date)- .order(:next_expected_date)- .limit(MAX_INSIGHTS)+ # Cycle-aware staleness: an occurrence is worth nagging about once a+ # WHOLE additional cycle has come due while it sits unpaid -- days for a+ # weekly bill, a month for a monthly one, never a false alarm for+ # quarterly and annual bills between their perfectly normal occurrences.+ # (The old flat 45-day threshold was six missed cycles for a weekly bill+ # and noise for an annual one.)+ def overdue_occurrences+ candidates = family.recurring_occurrences+ .open_status+ .joins(:recurring_transaction)+ .where(recurring_transactions: { status: :active, destination_account_id: nil })+ .where("recurring_transactions.amount > 0")+ .where("due_on < ?", Date.current)+ .includes(recurring_transaction: [ :merchant, :recurrence_rules ])+ .to_a++ stale = candidates.select do |occurrence|+ cycle_days = 365.25 / occurrence.recurring_transaction.schedule.occurrences_per_year+ (Date.current - occurrence.due_on).to_i >= [ cycle_days.round, 1 ].max+ end++ stale.group_by(&:recurring_transaction_id)+ .values+ .map { |group| group.min_by(&:due_on) }+ .sort_by(&:due_on)+ .first(MAX_INSIGHTS)endenddiff --git a/app/models/recurrence_rule.rb b/app/models/recurrence_rule.rbnew file mode 100644index 0000000000..c6af481134--- /dev/null+++ b/app/models/recurrence_rule.rb@@ -0,0 +1,50 @@+# 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+enddiff --git a/app/models/recurring_allocation.rb b/app/models/recurring_allocation.rbnew file mode 100644index 0000000000..fc1d3ae51c--- /dev/null+++ b/app/models/recurring_allocation.rb@@ -0,0 +1,41 @@+# One payment (or part of one) applied to one occurrence. Several allocations+# sum toward a single obligation -- that is the whole partial-payment model --+# and one entry may be split across several occurrences, each allocation+# carrying its own amount.+#+# entry_id is nullable by design: a payment recorded by hand (cash, or a bank+# feed that has not caught up) is a real payment with no entry. If an entry is+# later deleted, the FK nullifies rather than cascades, so the payment record+# and its amount survive.+class RecurringAllocation < ApplicationRecord+ include Monetizable++ belongs_to :recurring_occurrence+ belongs_to :entry, optional: true++ monetize :allocated_amount++ enum :state, { suggested: "suggested", confirmed: "confirmed" }, prefix: :allocation+ enum :source, { auto_matched: "auto_matched", user_confirmed: "user_confirmed",+ user_created: "user_created" }, prefix: :from++ validates :allocated_amount, presence: true, numericality: { greater_than: 0 }+ validates :currency, presence: true+ validate :currency_matches_occurrence++ scope :confirmed, -> { where(state: :confirmed) }+ scope :suggested, -> { where(state: :suggested) }++ before_validation :default_paid_on++ private+ def currency_matches_occurrence+ return if recurring_occurrence.nil? || currency == recurring_occurrence.currency++ errors.add(:currency, :must_match_occurrence)+ end++ def default_paid_on+ self.paid_on ||= entry&.date || Date.current+ end+enddiff --git a/app/models/recurring_match_rejection.rb b/app/models/recurring_match_rejection.rbnew file mode 100644index 0000000000..b131ff7f70--- /dev/null+++ b/app/models/recurring_match_rejection.rb@@ -0,0 +1,6 @@+# A (series, entry) pair the user rejected: the matcher must never suggest it+# again. Corrections are permanently sticky.+class RecurringMatchRejection < ApplicationRecord+ belongs_to :recurring_transaction+ belongs_to :entry+enddiff --git a/app/models/recurring_occurrence.rb b/app/models/recurring_occurrence.rbnew file mode 100644index 0000000000..b7122dadc1--- /dev/null+++ b/app/models/recurring_occurrence.rb@@ -0,0 +1,178 @@+# One expected instance of a recurring obligation: the August rent, this+# month's electric bill. Holds what is specific to the instance (due date,+# amount override, skip/snooze, payments via allocations); the rest inherits+# from the series.+#+# Stored status is minimal -- scheduled, plus the terminal paid / skipped /+# missed. Upcoming, due, overdue and partially paid all derive from dates and+# allocation sums, so they cannot drift stale. `missed` is only ever set by the+# user.+class RecurringOccurrence < ApplicationRecord+ include Monetizable++ # App defaults when the series leaves its per-bill knobs NULL.+ DEFAULT_NOTIFY_DAYS = 3+ DEFAULT_GRACE_DAYS = 3++ # Rounding epsilon for accumulation close: payments summing to within a+ # cent of the expected amount count as full payment.+ CLOSE_EPSILON = BigDecimal("0.01")++ belongs_to :recurring_transaction+ belongs_to :family+ has_many :allocations, class_name: "RecurringAllocation",+ foreign_key: :recurring_occurrence_id, dependent: :destroy, inverse_of: :recurring_occurrence++ monetize :expected_amount, allow_nil: true++ enum :status, { scheduled: "scheduled", paid: "paid", skipped: "skipped", missed: "missed" }++ validates :original_due_on, :due_on, :currency, presence: true+ validates :expected_amount, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true++ scope :open_status, -> { where(status: :scheduled) }+ scope :closed, -> { where.not(status: :scheduled) }+ scope :due_between, ->(from, to) { where(due_on: from..to) }++ # The amount this occurrence expects, resolving NULL through the series'+ # amount strategy, which is what lets a price edit update every open+ # occurrence with no sweep. `series_amount` overrides what the series says it+ # costs now, so a price change can pin what a row claimed before the edit.+ def resolved_expected_amount(series_amount: nil)+ return expected_amount if expected_amount.present?++ series = recurring_transaction+ fallback = series_amount || series.amount++ case series.amount_strategy+ when "average"+ series.expected_amount_avg.presence || fallback+ when "last"+ last_paid_total.presence || fallback+ else+ fallback+ end.abs+ end++ def resolved_expected_amount_money+ Money.new(resolved_expected_amount, currency)+ end++ # Snoozing postpones the presentation-level due date without rewriting the+ # schedule.+ def effective_due_on+ [ due_on, snoozed_until ].compact.max+ end++ # List views preload allocation sums in one grouped query and inject them+ # here, so row rendering issues no per-occurrence SUM.+ attr_writer :cached_confirmed_allocated++ def confirmed_allocated+ @cached_confirmed_allocated || allocations.confirmed.sum(:allocated_amount)+ end++ def confirmed_allocated_money+ Money.new(confirmed_allocated, currency)+ end++ def remaining_amount+ [ resolved_expected_amount - confirmed_allocated, 0 ].max+ end++ def remaining_amount_money+ Money.new(remaining_amount, currency)+ end++ # Exact sum, not tolerance: $1,850 allocated against $2,000 rent is+ # partially paid with $150 remaining, always.+ def partially_paid?+ scheduled? && confirmed_allocated.positive? && confirmed_allocated < resolved_expected_amount+ end++ def overpaid?+ confirmed_allocated > resolved_expected_amount + CLOSE_EPSILON+ end++ # Presentation state for open occurrences: upcoming until the notify+ # window, due through the grace period, overdue after it.+ def derived_state+ return status.to_sym unless scheduled?++ today = Date.current++ if today > effective_due_on + grace_days+ :overdue+ elsif today >= effective_due_on - notify_days+ :due+ else+ :upcoming+ end+ end++ def overdue?+ derived_state == :overdue+ end++ # --- Lifecycle actions. Closing freezes the resolved amount so the row is+ # self-contained history; reopening keeps that value as an explicit override+ # rather than un-freezing it. ---++ def close!(new_status, source:)+ update!(+ status: new_status,+ expected_amount: resolved_expected_amount,+ closed_at: Time.current,+ closed_source: source+ )+ end++ def skip!(source: "user")+ close!("skipped", source: source)+ end++ def miss!+ close!("missed", source: "user")+ end++ def reopen!+ update!(status: "scheduled", closed_at: nil, closed_source: nil)+ end++ def snooze!(until_date)+ update!(snoozed_until: until_date)+ end++ def override_amount!(amount)+ update!(expected_amount: amount.presence)+ end++ private+ def notify_days+ recurring_transaction.notify_days_before || DEFAULT_NOTIFY_DAYS+ end++ def grace_days+ recurring_transaction.overdue_grace_days || DEFAULT_GRACE_DAYS+ end++ # What the last settled cycle actually cost. `expected_amount` on a closed+ # row is the frozen estimate, so reading it would re-propose the guess and+ # strategy could never converge on a variable bill's real amount.+ # Memoized: every amount label on a row asks this same question.+ def last_paid_total+ return @last_paid_total if defined?(@last_paid_total)++ @last_paid_total = begin+ previous = recurring_transaction.recurring_occurrences+ .paid+ .where("due_on < ?", due_on)+ .order(due_on: :desc)+ .first+ if previous+ total = previous.allocations.confirmed.sum(:allocated_amount)+ total.positive? ? total : nil+ end+ end+ end+enddiff --git a/app/models/recurring_price_change.rb b/app/models/recurring_price_change.rbnew file mode 100644index 0000000000..03afd31f96--- /dev/null+++ b/app/models/recurring_price_change.rb@@ -0,0 +1,16 @@+# One observed price change on a series: previous amount, new amount, when it+# took effect, and the charge that revealed it. The rows are the series' price+# history, feeding subscription intelligence (price sparklines, "raised twice+# this year", annualized deltas).+class RecurringPriceChange < ApplicationRecord+ include Monetizable++ belongs_to :recurring_transaction+ belongs_to :entry, optional: true++ monetize :previous_amount, :new_amount++ enum :source, { detected: "detected", user: "user" }, prefix: :recorded_by++ validates :effective_on, :previous_amount, :new_amount, :currency, presence: true+enddiff --git a/app/models/recurring_transaction.rb b/app/models/recurring_transaction.rbindex 29ec28caf2..7d088bc2a1 100644--- a/app/models/recurring_transaction.rb+++ b/app/models/recurring_transaction.rb@@ -1,26 +1,125 @@+# Bills subsystem: this model gained recurrence rules, bill typing+# (bill / subscription / installment / income), payment and pay-run attributes,+# schedule pinning, and the payable scopes the Bills pages read.class RecurringTransaction < ApplicationRecordinclude Monetizable+ # Ceiling on how many occurrence rows one save can create: the generator+ # materialises a finite plan whole.+ MAX_END_AFTER_COUNT = 600+belongs_to :familybelongs_to :account, optional: truebelongs_to :destination_account, optional: true, class_name: "Account"belongs_to :merchant, optional: true+ belongs_to :category, optional: true+ belongs_to :replaced_by, optional: true, class_name: "RecurringTransaction"+ # autosave: FrequencyPreset marks old rules for destruction and builds+ # replacements in one assignment, and only autosave honors that on save.+ has_many :recurrence_rules, -> { order(:position) }, dependent: :destroy, autosave: true+ has_many :recurring_occurrences, dependent: :destroy+ has_many :recurring_match_rejections, dependent: :destroy+ has_many :recurring_price_changes, dependent: :destroymonetize :amountmonetize :expected_amount_min, allow_nil: truemonetize :expected_amount_max, allow_nil: truemonetize :expected_amount_avg, allow_nil: true- enum :status, { active: "active", inactive: "inactive" }+ # suggested: detector output awaiting user confirmation -- never surfaced as+ # a real bill, never generates occurrences.+ # paused: deliberately parked by the user; resumable.+ # inactive: auto-retired by the Cleaner after going stale.+ # ended: reached its end condition, was cancelled, or was dismissed from the+ # suggestion queue -- a tombstone the detector sees and will not recreate.+ enum :status, { suggested: "suggested", active: "active", paused: "paused",+ inactive: "inactive", ended: "ended" }+ enum :bill_type, { bill: "bill", subscription: "subscription", installment: "installment",+ income: "income", transfer: "transfer", other: "other" }, prefix: :typed+ enum :amount_strategy, { fixed: "fixed", average: "average", last: "last" }, prefix: :amount+ enum :end_mode, { never: "never", on_date: "on_date", after_count: "after_count" }, prefix: :ends+ enum :weekend_adjust, { none: "none", skip: "skip", before: "before", after: "after" }, prefix: :weekendvalidates :amount, presence: truevalidates :currency, presence: truevalidates :expected_day_of_month, presence: true, numericality: { greater_than: 0, less_than_or_equal_to: 31 }validates :status, presence: true, inclusion: { in: statuses.keys }validates :occurrence_count, numericality: { only_integer: true, greater_than_or_equal_to: 0 }+ # 600 covers a 50-year monthly plan and a 10-year weekly one.+ validates :end_after_count,+ numericality: { only_integer: true, greater_than: 0, less_than_or_equal_to: MAX_END_AFTER_COUNT },+ allow_nil: truevalidate :merchant_or_name_present+ validate :category_belongs_to_family+ validate :accounts_belong_to_familyvalidate :amount_variance_consistencyvalidate :transfer_endpoints_consistent+ validate :payment_url_is_http+ validate :anchor_required_for_intervals+ validate :end_mode_fields_consistent+ validate :bill_type_matches_shape++ normalizes :payment_url, with: ->(url) { normalize_payment_url(url) }++ before_validation :derive_transfer_bill_type++ # Columns whose change reshapes the occurrence stream. Amount is absent on+ # purpose: open occurrences inherit it at read time.+ SCHEDULE_SHAPING_ATTRIBUTES = %w[+ expected_day_of_month anchor_date end_mode end_on end_after_count weekend_adjust status currency+ ].freeze++ # Set by FrequencyPreset when it rewrites the rules; cleared after the+ # post-commit regeneration consumes it.+ attr_accessor :rules_rewritten++ after_commit :generate_occurrences, on: :create+ after_commit :regenerate_future_occurrences, on: :update, if: :schedule_shape_changed?+ after_commit :pin_amount_on_dates_already_due, on: :update, if: :saved_change_to_amount?++ # Form state for the frequency picker and the create-bill dialog;+ # FrequencyPreset and the controller translate these on save. Not persisted.+ attr_accessor :frequency_preset, :frequency_day_of_month, :frequency_second_day_of_month,+ :frequency_weekday, :frequency_month_of_year, :first_due_on, :is_income++ # A scheme, followed by either "//" or by something that is not a port number.+ # "example.com:8080" is a host and port, not a scheme, so it does not match.+ EXPLICIT_SCHEME = %r{\A[a-zA-Z][a-zA-Z0-9+.\-]*:(?://|(?!\d))}++ # A bare host is promoted to https; anything with an explicit scheme is left+ # exactly as typed so validation rejects it on the merits rather than by+ # accident of URI parsing. Mirrors FamilyMerchant#extract_domain.+ def self.normalize_payment_url(url)+ stripped = url.to_s.strip+ return nil if stripped.blank?+ return stripped if stripped.match?(EXPLICIT_SCHEME)++ "https://#{stripped}"+ end++ # The scheme allowlist is the security boundary: it is what keeps a stored+ # "javascript:" or "data:" URL from becoming XSS when rendered as a link.+ # URI::HTTPS subclasses URI::HTTP, so this one check accepts both schemes and+ # nothing else. The host check rejects a bare "https://".+ def self.valid_payment_url?(url)+ return false if url.blank?++ uri = URI.parse(url)+ uri.is_a?(URI::HTTP) && uri.host.present?+ rescue URI::InvalidURIError+ false+ end++ def payment_url?+ payment_url.present?+ end++ # What the user calls this bill, which is a different question from what it+ # matches on: a typed name wins over the detected merchant, while the matcher+ # keeps reading the merchant directly.+ def display_name+ name.presence || merchant&.name+ enddef merchant_or_name_presentif merchant_id.blank? && name.blank?@@ -28,12 +127,103 @@ class RecurringTransaction < ApplicationRecordendend- def amount_variance_consistency- return unless manual?+ # category_id is mass-assignable and nothing else checks ownership, so a+ # crafted id would attach another family's category to this bill.+ def category_belongs_to_family+ return if category_id.blank? || family_id.blank?++ unless Category.where(id: category_id, family_id: family_id).exists?+ errors.add(:category_id, :invalid)+ end+ end+ # account_id and destination_account_id are mass-assignable like category_id,+ # so a crafted id could attach another family's account to this bill --+ # transfer_endpoints_consistent only compares the endpoints to each other.+ def accounts_belong_to_family+ return if family_id.blank?++ { account: account, destination_account: destination_account }.each do |attribute, record|+ next if record.blank? || record.family_id == family_id++ errors.add(attribute, :wrong_family)+ end+ end++ def payment_url_is_http+ return if payment_url.blank?++ errors.add(:payment_url, :invalid_scheme) unless self.class.valid_payment_url?(payment_url)+ end++ def generate_occurrences+ OccurrenceGenerator.new(self).generate!+ end++ # Regenerating rebuilds only scheduled, allocation-free, not-yet-due rows;+ # anything closed or carrying payments is untouched.+ def regenerate_future_occurrences+ self.rules_rewritten = false+ OccurrenceGenerator.new(self).regenerate_future!+ end++ def schedule_shape_changed?+ rules_rewritten || (previous_changes.keys & SCHEDULE_SHAPING_ATTRIBUTES).any?+ end++ # A price change applies from now on, not retroactively. Occurrences resolve+ # their amount from the series live, so dates already due are stamped with what+ # they claimed while future ones pick up the new amount. Rows carrying a+ # payment are already pinned by the allocator.+ def pin_amount_on_dates_already_due+ was = previous_changes["amount"]&.first+ return if was.blank?++ recurring_occurrences+ .open_status+ .where(expected_amount: nil)+ .where("due_on <= ?", Date.current)+ .find_each do |occurrence|+ occurrence.update!(expected_amount: occurrence.resolved_expected_amount(series_amount: was))+ end+ end++ # A destination account is the definition of a transfer, so the type derives+ # from the shape rather than every creation path remembering to set it.+ def derive_transfer_bill_type+ self.bill_type = "transfer" if transfer?+ end++ def bill_type_matches_shape+ if typed_transfer? && !transfer?+ errors.add(:bill_type, :transfer_shape_mismatch)+ end+ end++ # An "every N periods" cadence is a phase-shifted grid: without a reference+ # occurrence there is no way to say WHICH biweekly Friday is the right one.+ def anchor_required_for_intervals+ return if anchor_date.present?+ return unless recurrence_rules.reject(&:marked_for_destruction?).any? { |rule| rule.interval.to_i > 1 }++ errors.add(:anchor_date, :required_for_intervals)+ end++ def end_mode_fields_consistent+ case end_mode+ when "on_date"+ errors.add(:end_on, :blank) if end_on.blank?+ when "after_count"+ if end_after_count.blank? || end_after_count.to_i < 1+ errors.add(:end_after_count, :blank)+ end+ end+ end++ def amount_variance_consistencyif expected_amount_min.present? && expected_amount_max.present?if expected_amount_min > expected_amount_max- errors.add(:expected_amount_min, "cannot be greater than expected_amount_max")+ errors.add(:expected_amount_min, :greater_than_max)endendend@@ -44,21 +234,21 @@ class RecurringTransaction < ApplicationRecordreturn if destination_account_id.blank?if account_id.blank?- errors.add(:account, "must be present on a recurring transfer")+ errors.add(:account, :required_for_transfer)elsif account.blank?# account_id references a row that was destroyed. Mirror the# destination_account.blank? branch so the source side surfaces a- # normal validation error too.- errors.add(:account, "must exist")+ # normal validation error too. :required is the stock "must exist".+ errors.add(:account, :required)elsif destination_account.blank?# destination_account_id references a row that was destroyed (or never# existed). Surface as a normal validation error instead of letting# the FK fire on save.- errors.add(:destination_account, "must exist")+ errors.add(:destination_account, :required)elsif account_id == destination_account_id- errors.add(:destination_account, "cannot be the same as the source account")+ errors.add(:destination_account, :same_as_source)elsif account.family_id != destination_account.family_id- errors.add(:destination_account, "must belong to the same family as the source account")+ errors.add(:destination_account, :family_mismatch)endend@@ -68,6 +258,124 @@ class RecurringTransaction < ApplicationRecordscope :for_family, ->(family) { where(family: family) }scope :expected_soon, -> { active.where("next_expected_date <= ?", 1.month.from_now) }++ # An active recurring expense you owe someone: transfers are internal moves and+ # income is not owed, so neither belongs on a list of things to pay. No minimum+ # amount, since any threshold is wrong in some currency; pause handles the rest.+ scope :bills, -> { active.where(destination_account_id: nil).where("amount > 0") }++ # Everything the Bills page owes an answer for: expense bills and+ # subscriptions, PLUS recurring transfers into liability accounts -- a+ # credit-card or loan payment is a real obligation with a real due date,+ # even though it is a transfer and not spending. (It stays excluded from+ # any budget/category math for exactly that reason.)+ scope :payable, -> {+ # Correlated to the row rather than a free-standing id list: the bare+ # subquery scanned every account in the installation on every call, and+ # the destination must belong to the series' own family.+ debt_destination = Account.where(accountable_type: %w[CreditCard Loan])+ .where("accounts.id = recurring_transactions.destination_account_id")+ .where("accounts.family_id = recurring_transactions.family_id")++ active.where("amount > 0")+ .merge(where(destination_account_id: nil).or(where(debt_destination.arel.exists)))+ }++ # The bills that want an action from you. Autopay bills still belong on the+ # list, but they are not tasks.+ scope :needs_action, -> { where(autopay: false) }++ # Derived rather than read from the stored `next_expected_date`, which can sit+ # a cycle too far out when a payment posts earlier than the expected day.+ # For installment plans: how many payments are done, out of how many.+ # nil when the series has no declared payment count.+ def installment_progress+ return nil unless typed_installment? && end_after_count.present?++ [ recurring_occurrences.paid.count, end_after_count ]+ end++ # The occurrence the user most needs to see: the earliest still-open one+ # (which is also the most overdue), falling back to the most recent closed+ # one when everything is settled.+ # Preload-aware: get_bills and the bills page both include occurrences, and+ # this runs once per row.+ def next_open_occurrence+ if recurring_occurrences.loaded?+ recurring_occurrences.select(&:scheduled?).min_by(&:due_on)+ else+ recurring_occurrences.open_status.order(:due_on).first+ end+ end++ def current_occurrence+ recurring_occurrences.open_status.order(:due_on).first ||+ recurring_occurrences.order(due_on: :desc).first+ end++ # The occurrences are the schedule. They are what the app materializes,+ # settles, displays and reports on, so the next one still open is what this+ # bill is actually waiting for.+ #+ # next_expected_date is only a cached hint, and the sole paths that advance+ # it are a sync-time match against a real bank entry and record_occurrence!,+ # which nothing calls. Settle a bill any other way, through mark_paid!, a+ # manual payment or the assistant, and the hint froze on a date in the past+ # for good. This method returned it verbatim, so a fully paid bill reported a+ # due date 45 days gone, answered due_within_days: 3, and was filed as two+ # cycles overdue while its own occurrence sat upcoming.+ #+ # The hint still serves as the fallback for a series with nothing+ # materialized yet.+ def next_due_date+ occurrence = next_open_occurrence+ return occurrence.effective_due_on if occurrence++ return next_expected_date if next_expected_date <= Date.current++ [ next_expected_date, schedule.next_occurrence_from_today ].compact.min+ end++ def overdue?+ next_due_date < Date.current+ end++ # This bill's cost normalized to a per-month figure, whatever its cadence:+ # a $120 annual bill contributes $10, a $10 weekly bill about $43.45. This+ # is the honest number for "recurring commitment" style totals; summing raw+ # amounts across mixed cadences answers no meaningful question.+ def monthly_equivalent_amount+ amount_money * (schedule.occurrences_per_year / 12.0)+ end++ # The newest price changes, most recent first. Sorts in Ruby when a caller+ # preloaded the association so the detail panel costs no extra query.+ def recent_price_changes(count = 5)+ if recurring_price_changes.loaded?+ recurring_price_changes.sort_by(&:effective_on).reverse.first(count)+ else+ recurring_price_changes.order(effective_on: :desc).limit(count)+ end+ end++ # Deliberately strict -- same name ignoring case and spacing, same amount AND+ # same expected day -- so concurrent subscription tiers to one merchant are+ # never flagged as duplicates of each other.+ def duplicate_key+ [ display_name.to_s.downcase.gsub(/\s+/, " ").strip, amount, expected_day_of_month ]+ end++ # How many whole cycles have elapsed since this was due, using the series'+ # real cadence length. Whole is meant literally: a bill one day late has not+ # yet missed a cycle. The trailing +1 this used to carry reported 1 on the+ # first day late, which put a bill inside its own grace period into a section+ # documented as "overdue by at least one whole billing cycle".+ def cycles_overdue+ return 0 unless overdue?++ cycle_days = 365.25 / schedule.occurrences_per_year+ ((Date.current - next_due_date).to_i / cycle_days).floor+ endscope :accessible_by, ->(user) {accessible_account_ids = Account.accessible_by(user).select(:id)# A recurring row is accessible when:@@ -133,6 +441,7 @@ class RecurringTransaction < ApplicationRecordlast_occurrence_date: outflow_entry.date,next_expected_date: next_expected,status: "active",+ bill_type: "transfer",occurrence_count: 1,manual: true)@@ -190,23 +499,33 @@ class RecurringTransaction < ApplicationRecord# Calculate next expected date relative to today, not the transaction datenext_expected = calculate_next_expected_date_from_today(expected_day)- create!(+ attributes = {family: family,account: entry.account,merchant_id: transaction.merchant_id,name: transaction.merchant_id.present? ? nil : entry.name,amount: entry.amount,+ # Identity no longer includes amount, so a second legitimate series for+ # one merchant (another price tier) is distinguished by stamping its+ # amount into dedup_scope before the first insert. The same identity at+ # the same amount then collides immediately instead of slipping past as+ # a duplicate; callers treat the raised RecordNotUnique as "already+ # exists".+ dedup_scope: entry.amount.to_d.to_s("F"),currency: entry.currency,expected_day_of_month: expected_day,last_occurrence_date: entry.date,next_expected_date: next_expected,status: "active",+ bill_type: entry.amount.negative? ? "income" : "bill",occurrence_count: matching_amounts.size,manual: true,expected_amount_min: expected_min,expected_amount_max: expected_max,expected_amount_avg: expected_avg- )+ }++ create!(attributes)end# Find matching transaction entries for variance calculation@@ -218,9 +537,9 @@ class RecurringTransaction < ApplicationRecord.where(entryable_type: "Transaction").where(currency: currency).where("entries.date >= ?", lookback_date)- .where("EXTRACT(DAY FROM entries.date) BETWEEN ? AND ?",- [ expected_day - 2, 1 ].max,- [ expected_day + 2, 31 ].min)+ .where(Schedule.day_window_sql,+ expected_day: expected_day,+ tolerance: Schedule::DAY_MATCH_TOLERANCE)# Only entries whose amount is within the variance band of the target# amount count as "the same fluctuating payment" — otherwise unrelated# charges that happen to share a merchant/day get averaged together@@ -258,34 +577,22 @@ class RecurringTransaction < ApplicationRecord# Calculate next expected date from todaydef self.calculate_next_expected_date_from_today(expected_day)- today = Date.current-- # Try this month first- begin- this_month_date = Date.new(today.year, today.month, expected_day)- return this_month_date if this_month_date > today- rescue ArgumentError- # Day doesn't exist in this month (e.g., 31st in February)- end-- # Otherwise use next month- calculate_next_expected_date_for(today, expected_day)+ Schedule.new(expected_day_of_month: expected_day).next_occurrence_from_todayenddef self.calculate_next_expected_date_for(from_date, expected_day)- next_month = from_date.next_month- begin- Date.new(next_month.year, next_month.month, expected_day)- rescue ArgumentError- next_month.end_of_month- end+ Schedule.new(expected_day_of_month: expected_day).next_occurrence_after(from_date)end- # Find matching transactions for this recurring pattern+ # Find matching transactions for this recurring pattern. SQL narrows to+ # amount/day-window candidates; the schedule then keeps only entries on a+ # real occurrence, so an every-N cadence sheds same-day charges from+ # off-cycle periods (which would keep a dead series alive in Cleaner and+ # pollute variance samples).def matching_transactions# Recurring transfers can't be matched by single-account name/amount —# future occurrences carry arbitrary names — so match the Transfer pair.- return transfer_matching_transactions if transfer?+ return schedule_matched(transfer_matching_transactions) if transfer?# Amount/cadence-scoped Transaction entries on this account (or family).base = account.present? ? account.entries : family.entries@@ -294,28 +601,55 @@ class RecurringTransaction < ApplicationRecord).order(date: :desc)# Filter by merchant or name- if merchant_id.present?+ candidates = if merchant_id.present?# Match by merchant through the entryable (Transaction)- entries.select do |entry|+ entries.includes(:entryable).select do |entry|entry.entryable.is_a?(Transaction) && entry.entryable.merchant_id == merchant_idendelse# Match by entry nameentries.where(name: name)end++ schedule_matched(candidates)end- # Check if this recurring transaction has amount variance configured+ # True only when the observed amounts actually spread. Detection records a band+ # for every cluster, so a stable bill carries a degenerate one (min == max) that+ # must not render as "~amount".def has_amount_variance?- expected_amount_min.present? && expected_amount_max.present?+ expected_amount_min.present? && expected_amount_max.present? &&+ expected_amount_min < expected_amount_max+ end++ # Stale after two missed cycles of the series' own cadence, floored at 2 months+ # (auto) / 6 months (manual), so quarterly and annual bills survive the gaps+ # between their normal occurrences.+ def staleness_threshold_date+ calendar_floor = (manual? ? 6 : 2).months.ago.to_date+ cycle_days = (2 * 365.25 / schedule.occurrences_per_year).ceil++ [ calendar_floor, cycle_days.days.ago.to_date ].minend# Check if this recurring transaction should be marked inactivedef should_be_inactive?return false if last_occurrence_date.nil?- # Manual recurring transactions have a longer threshold- threshold = manual? ? 6.months.ago : 2.months.ago- last_occurrence_date < threshold++ last_occurrence_date < staleness_threshold_date+ end++ # A cadence the user typed is intent; the dates charges land on are+ # observation. Detection keeps refreshing the latter but must not move a+ # schedule someone set by hand. `manual` cannot carry this: it is set at+ # creation and no edit flips it.+ def schedule_pinned?+ matcher_hints.to_h["schedule_pinned_at"].present?+ end++ # Assigns rather than saves: callers are mid-edit and persist the record.+ def pin_schedule+ self.matcher_hints = matcher_hints.to_h.merge("schedule_pinned_at" => Time.current.iso8601)end# Mark as inactive@@ -365,18 +699,15 @@ class RecurringTransaction < ApplicationRecordself.expected_amount_avg = expected_amount_avg + ((transaction_amount - expected_amount_avg) / (n + 1))end+ # All date math is owned by Schedule; the model keeps thin, signature-stable+ # delegators for its existing callers.+ def schedule+ Schedule.for(self)+ end+# Calculate the next expected date based on the last occurrencedef calculate_next_expected_date(from_date = last_occurrence_date)- # Start with next month- next_month = from_date.next_month-- # Try to use the expected day of month- begin- Date.new(next_month.year, next_month.month, expected_day_of_month)- rescue ArgumentError- # If day doesn't exist in month (e.g., 31st in February), use last day of month- next_month.end_of_month- end+ schedule.next_occurrence_after(from_date)end# Get the projected transaction for display@@ -435,20 +766,29 @@ class RecurringTransaction < ApplicationRecordend# Transaction entries whose amount fits the pattern: exact, or within the- # configured variance band for manual recurring rows.+ # observed variance band when one has been recorded.def amount_window_scope(relation)- if manual? && has_amount_variance?+ if has_amount_variance?relation.where("entries.amount BETWEEN ? AND ?", expected_amount_min, expected_amount_max)elserelation.where("entries.amount = ?", amount)endend- # Entries whose day-of-month lands within ±2 days of the expected day.+ # Ruby-side completion of day_of_month_scope: the SQL window only knows+ # the calendar day, so the full schedule (interval phase, weekday, end+ # conditions, weekend adjustment) prunes the candidates here.+ def schedule_matched(entries)+ full_schedule = schedule+ entries.select { |entry| full_schedule.matches_day?(entry.date) }+ end++ # Entries landing within the schedule's day tolerance, on the circular+ # calendar with short-month clamping.def day_of_month_scope(relation)- relation.where("EXTRACT(DAY FROM entries.date) BETWEEN ? AND ?",- [ expected_day_of_month - 2, 1 ].max,- [ expected_day_of_month + 2, 31 ].min)+ relation.where(Schedule.day_window_sql,+ expected_day: expected_day_of_month,+ tolerance: Schedule::DAY_MATCH_TOLERANCE)enddef monetizable_currencydiff --git a/app/models/recurring_transaction/allocator.rb b/app/models/recurring_transaction/allocator.rbnew file mode 100644index 0000000000..cb2ad58dbf--- /dev/null+++ b/app/models/recurring_transaction/allocator.rb@@ -0,0 +1,349 @@+class RecurringTransaction+ # The only supported write path for allocations: it holds the locks, freezes+ # the amount, and refreshes close state. A direct RecurringAllocation.create!+ # bypasses all three.+ #+ # Every write takes the occurrence row lock. Writes touching an entry also+ # take an advisory lock on the ENTRY, because two allocations of one+ # transaction against two different occurrences take different row locks,+ # never meet, and would both read the same stale capacity.+ #+ # Closing has two modes, and conflating them marks half-paid rent as settled:+ #+ # * Actual-replaces-estimate: a SINGLE payment within the series' tolerance+ # of the expected amount is the bill. Close paid.+ # * Accumulation: multiple payments, or one below the band, close only when+ # they sum to the full expected amount.+ class Allocator+ class OverAllocationError < StandardError; end+ class MissingRateError < StandardError; end++ # Postgres keeps single-key and two-key advisory locks in separate spaces,+ # so this cannot collide with the single-key family locks the jobs take.+ ENTRY_LOCK_NAMESPACE = 8311++ attr_reader :occurrence++ def initialize(occurrence)+ @occurrence = occurrence+ end++ # Records a payment: against an entry (full or custom amount) or as an+ # entry-less manual payment. Amounts are in the occurrence's currency;+ # a cross-currency entry converts at its own date's rate, or requires an+ # explicit amount when no rate exists.+ def allocate!(amount: nil, entry: nil, paid_on: nil, source: nil)+ occurrence.with_lock do+ with_entry_lock(entry) do+ allocated, source_amount, source_currency = resolve_amounts(amount, entry)+ guard_entry_capacity!(entry, source_amount) if entry+ freeze_expected_amount!++ allocation = occurrence.allocations.create!(+ entry: entry,+ allocated_amount: allocated,+ currency: occurrence.currency,+ source_amount: source_amount,+ source_currency: source_currency,+ state: "confirmed",+ source: source || (entry ? "user_confirmed" : "user_created"),+ paid_on: paid_on+ )++ learn_from_manual_attach!(allocation) if entry+ refresh_close_state!+ allocation+ end+ end+ end++ def unallocate!(allocation)+ occurrence.with_lock do+ with_entry_lock(allocation.entry) do+ allocation.destroy!+ refresh_close_state!+ end+ end+ end++ # The Matcher's write path: confirmed at the exact tier, suggested at the+ # high tier. Suggestions never move close state.+ def allocate_matched!(entry:, state:, confidence:, signals:)+ occurrence.with_lock do+ with_entry_lock(entry) do+ allocated, source_amount, source_currency = resolve_amounts(nil, entry)+ return nil unless allocated.positive?++ guard_entry_capacity!(entry, source_amount)+ freeze_expected_amount! if state == "confirmed"++ allocation = occurrence.allocations.create!(+ entry: entry,+ allocated_amount: allocated,+ currency: occurrence.currency,+ source_amount: source_amount,+ source_currency: source_currency,+ state: state,+ source: "auto_matched",+ match_confidence: confidence,+ match_signals: signals,+ paid_on: entry.date+ )++ refresh_close_state! if state == "confirmed"+ allocation+ end+ end+ end++ # Accepting a suggestion makes it a real payment.+ def confirm_suggestion!(allocation)+ occurrence.with_lock do+ with_entry_lock(allocation.entry) do+ freeze_expected_amount!+ allocation.update!(state: "confirmed", source: "user_confirmed")+ refresh_close_state!+ end+ end+ end++ # Records the (series, entry) pair so the matcher never proposes it again.+ def reject_suggestion!(allocation)+ occurrence.with_lock do+ with_entry_lock(allocation.entry) do+ if allocation.entry+ RecurringMatchRejection.find_or_create_by!(+ recurring_transaction: occurrence.recurring_transaction,+ entry: allocation.entry+ )+ end++ allocation.destroy!+ end+ end+ end++ # Settles the remainder with no transaction, as a user decision, so it+ # never auto-reopens. A backdated settlement carries its real payment date+ # into the history instead of defaulting to today.+ def mark_paid!(paid_on: nil)+ occurrence.with_lock do+ freeze_expected_amount!+ remaining = occurrence.remaining_amount++ if remaining.positive?+ occurrence.allocations.create!(+ allocated_amount: remaining,+ currency: occurrence.currency,+ state: "confirmed",+ source: "user_created",+ paid_on: paid_on+ )+ end++ occurrence.reload+ occurrence.close!("paid", source: "user") if occurrence.scheduled?+ end+ end++ # Re-derives the stored close state from the confirmed allocations:+ # closes an open occurrence that now qualifies, reopens an auto-closed one+ # that no longer does. User-closed occurrences never auto-reopen.+ def refresh_close_state!+ occurrence.reload++ if occurrence.scheduled?+ occurrence.close!("paid", source: "auto") if close_worthy?+ elsif occurrence.paid? && occurrence.closed_source == "auto" && !close_worthy?+ occurrence.reopen!+ end+ end++ private+ # Serializes every write touching this entry, whichever occurrence it+ # targets. Always taken inside the occurrence row lock, so the ordering is+ # occurrence then entry and no pair can deadlock.+ def with_entry_lock(entry)+ return yield if entry.nil?++ occurrence.class.lease_connection.execute(+ ActiveRecord::Base.sanitize_sql_array(+ [ "SELECT pg_advisory_xact_lock(?::int, ?::int)", ENTRY_LOCK_NAMESPACE, entry_lock_id(entry) ]+ )+ )++ yield+ end++ def entry_lock_id(entry)+ Digest::MD5.hexdigest(entry.id.to_s).to_i(16) % (2**31)+ end++ # A confirmed payment pins the obligation it was made against. Open rows+ # otherwise inherit their amount from the series, which is correct until+ # money has moved: after that, re-resolving would re-target a payment the+ # user already made. Suggestions pin nothing.+ def freeze_expected_amount!+ return if occurrence.expected_amount.present?++ occurrence.update!(expected_amount: occurrence.resolved_expected_amount)+ end++ def close_worthy?+ expected = occurrence.resolved_expected_amount+ return false unless expected.positive?++ confirmed = occurrence.allocations.confirmed.to_a+ return false if confirmed.empty?++ total = confirmed.sum(&:allocated_amount)++ if confirmed.size == 1+ tolerance = expected * (occurrence.recurring_transaction.amount_tolerance_pct / BigDecimal("100"))+ return true if (confirmed.first.allocated_amount - expected).abs <= tolerance+ end++ total >= expected - RecurringOccurrence::CLOSE_EPSILON+ end++ def resolve_amounts(amount, entry)+ if entry.nil?+ raise ArgumentError, "an amount is required for a payment without a transaction" if amount.blank?++ return [ BigDecimal(amount.to_s), nil, nil ]+ end++ entry_total = entry.amount.abs++ if entry.currency == occurrence.currency+ allocated = if amount.present?+ BigDecimal(amount.to_s)+ else+ # Default: as much of the entry as this occurrence still needs --+ # or, when the occurrence is already covered, the entry's whole+ # unspoken-for amount (an explicit overpay attach). Either way it+ # is bounded by what the entry has left: an exhausted entry+ # allocates nothing, never the occurrence's outstanding balance.+ capacity = entry_capacity(entry, entry_total)+ remaining = occurrence.remaining_amount+ remaining.positive? ? [ capacity, remaining ].min : capacity+ end++ [ allocated, allocated, entry.currency ]+ else+ rate = ExchangeRate.find_or_fetch_rate(from: entry.currency, to: occurrence.currency, date: entry.date)&.rate++ if amount.present?+ allocated = BigDecimal(amount.to_s)+ source = rate ? (allocated / BigDecimal(rate.to_s)).round(4) : nil+ [ allocated, source, entry.currency ]+ elsif rate+ # Bounded the same way the same-currency default is: by what is+ # left of the entry and what the occurrence still owes. Defaulting+ # to the entry's full total meant a partly allocated foreign+ # transaction could never be attached without an explicit amount,+ # because the guard rejected the untaken remainder's own default.+ source = entry_capacity(entry, entry_total)+ converted = (source * BigDecimal(rate.to_s)).round(4)+ remaining = occurrence.remaining_amount++ if remaining.positive? && remaining < converted+ [ remaining, (remaining / BigDecimal(rate.to_s)).round(4), entry.currency ]+ else+ [ converted, source, entry.currency ]+ end+ else+ raise MissingRateError, I18n.t("recurring_transactions.allocator.missing_rate",+ from: entry.currency, to: occurrence.currency)+ end+ end+ end++ # True once any allocation on this entry lacks a source amount, which+ # makes every capacity sum over it meaningless.+ def unmeasurable_entry?(entry)+ RecurringAllocation.where(entry: entry, source_amount: nil).exists?+ end++ # How much of the entry is not yet spoken for, in the entry's currency.+ def entry_capacity(entry, entry_total)+ already = RecurringAllocation.where(entry: entry).sum(+ "COALESCE(source_amount, allocated_amount)"+ )++ [ entry_total - already, 0 ].max+ end++ # Two transparent things a manual attach can teach the matcher, both+ # stored in the series' user-visible matcher_hints:+ #+ # * An alias: a name-keyed series attached to an entry it would not+ # have recognized -- next time the matcher will.+ # * A wider tolerance: when this SINGLE entry essentially is the bill+ # and its amount sits outside the band, the band was too tight.+ # Partial payments teach nothing -- a $537.50 installment against+ # $2,150 rent is not evidence that rent varies. Being the only+ # allocation does not make a payment the bill, so the test is+ # whether it actually SETTLES the occurrence.+ def learn_from_manual_attach!(allocation)+ series = occurrence.recurring_transaction+ entry = allocation.entry+ hints = series.matcher_hints.deep_dup++ if series.merchant_id.blank? && series.name.present?+ known = ([ series.name ] + Array(hints["name_aliases"]))+ .map { |name| Matcher.normalize_name(name) }++ unless known.include?(Matcher.normalize_name(entry.name))+ hints["name_aliases"] = (Array(hints["name_aliases"]) + [ entry.name ]).uniq+ end+ end++ expected = occurrence.resolved_expected_amount+ if expected.positive? && occurrence.allocations.confirmed.count == 1 && close_worthy?+ deviation_pct = (entry.amount.abs - expected).abs / expected * 100+ current = BigDecimal((hints["learned_tolerance_pct"] || 0).to_s)++ if deviation_pct > series.amount_tolerance_pct &&+ deviation_pct > current &&+ deviation_pct <= Matcher::MAX_LEARNED_TOLERANCE_PCT+ hints["learned_tolerance_pct"] = deviation_pct.round(1).to_f+ end+ end++ series.update!(matcher_hints: hints) if hints != series.matcher_hints+ end++ # One transaction can pay several occurrences, but never more than+ # itself. Compared in the ENTRY's currency via source_amount.+ #+ # An allocation with no exchange rate for its date has no source amount,+ # so it cannot be expressed in the entry's currency, and neither it nor+ # anything beside it can be measured against the transaction total.+ # Exempting those outright meant a single 100 EUR transaction could be+ # allocated 150 USD twice over, and indeed without limit: capacity summed+ # COALESCE(source_amount, allocated_amount), mixing currencies into a+ # number that meant nothing.+ #+ # The first such allocation is a judgement the user made about a+ # transaction they can see. A second one is a transaction silently paying+ # an unbounded number of bills, so an unmeasurable entry takes no more+ # than one.+ def guard_entry_capacity!(entry, source_amount)+ if source_amount.nil? || unmeasurable_entry?(entry)+ return if RecurringAllocation.where(entry: entry).none?++ raise OverAllocationError, I18n.t("recurring_transactions.allocator.unmeasurable",+ currency: entry.currency, date: entry.date)+ end++ capacity = entry_capacity(entry, entry.amount.abs)++ if source_amount > capacity + RecurringOccurrence::CLOSE_EPSILON+ raise OverAllocationError, I18n.t("recurring_transactions.allocator.over_allocated",+ amount: source_amount, capacity: capacity,+ currency: entry.currency)+ end+ end+ end+enddiff --git a/app/models/recurring_transaction/classifier.rb b/app/models/recurring_transaction/classifier.rbnew file mode 100644index 0000000000..3ebeea7995--- /dev/null+++ b/app/models/recurring_transaction/classifier.rb@@ -0,0 +1,120 @@+class RecurringTransaction+ # Rule-based first guess at what a detected charge is: a subscription (a+ # service auto-charging a card on file) or a bill (an obligation you push+ # money at). Transparent by design -- keyword lists and three heuristics, no+ # scoring -- and only a default, since Kind stays user-editable and detection+ # never reclassifies after creation.+ #+ # Category is inherited from the most common one across the cluster's+ # entries.+ class Classifier+ # Services that are subscriptions essentially always.+ SUBSCRIPTION_KEYWORDS = %w[+ netflix spotify hulu disney hbo hbo\ max paramount peacock crunchyroll+ youtube prime audible kindle icloud apple.com/bill google\ one+ playstation xbox nintendo twitch patreon substack onlyfans+ dropbox github openai anthropic claude chatgpt midjourney canva adobe+ microsoft\ 365 office\ 365 notion slack zoom 1password lastpass+ bitwarden nordvpn expressvpn sirius pandora tidal deezer duolingo+ headspace calm grammarly peloton planet\ fitness la\ fitness+ grok x.ai xai+ ].freeze++ # Wording that marks classic push-payment obligations: utilities,+ # telecom, insurance, housing, taxes.+ BILL_KEYWORDS = %w[+ electric power energy gas water sewer utility utilit* insurance insur*+ mortgage rent lease loan hoa property tax comcast xfinity spectrum+ cox centurylink frontier at&t verizon t-mobile tmobile mint\ mobile+ wireless phone internet interest finance\ charge+ ].freeze++ # Buy-now-pay-later and financing: a fixed run of payments, then done.+ INSTALLMENT_KEYWORDS = %w[klarna affirm afterpay sezzle zip\ pay uplift].freeze++ # Push-payment fingerprints in raw descriptors.+ ACH_MARKERS = %w[ach web\ pmt webpmt billpay bill\ pay online\ pmt e-pay epay].freeze++ # Above this, a flat recurring charge is more likely rent-or-service+ # than a streaming plan.+ SUBSCRIPTION_AMOUNT_CEILING = BigDecimal("150")++ Result = Data.define(:bill_type, :category_id, :autopay)++ def self.classify(name:, entries:, account: nil)+ new(name: name, entries: entries, account: account).classify+ end++ attr_reader :name, :entries, :account++ def initialize(name:, entries:, account: nil)+ @name = name.to_s.downcase+ @entries = entries+ @account = account+ end++ def classify+ kind =+ if matches?(INSTALLMENT_KEYWORDS)+ "installment"+ elsif subscription?+ "subscription"+ else+ "bill"+ end++ Result.new(+ bill_type: kind,+ category_id: modal_category_id,+ # Subscriptions and BNPL plans are auto-charges: on the list, not a+ # task.+ autopay: kind != "bill"+ )+ end++ private+ def subscription?+ return false if matches?(BILL_KEYWORDS) || matches?(ACH_MARKERS)+ return true if matches?(SUBSCRIPTION_KEYWORDS)++ # No name signal: an identical-to-the-cent modest charge on a credit+ # card is the shape of a card-on-file service.+ flat_amounts? && modest_amount? && credit_card_account?+ end++ # Whole words only. A substring test let "max" claim Maxwell Plumbing+ # and "gas" claim a gastropub, and a false subscription match also set+ # autopay, which removes the row from the needs-action list. A trailing+ # "*" marks a stem that may carry a suffix, so "utilit*" still reaches+ # "UTILITIES" without a bare stem matching inside unrelated words.+ def matches?(keywords)+ keywords.any? do |keyword|+ if keyword.end_with?("*")+ name.match?(/\b#{Regexp.escape(keyword.delete_suffix('*'))}\w*/)+ else+ name.match?(/\b#{Regexp.escape(keyword)}\b/)+ end+ end+ end++ def flat_amounts?+ amounts = entries.map { |entry| entry.amount.abs }+ amounts.uniq.size == 1+ end++ def modest_amount?+ entries.first.amount.abs <= SUBSCRIPTION_AMOUNT_CEILING+ end++ def credit_card_account?+ account&.accountable_type == "CreditCard"+ end++ def modal_category_id+ entries.filter_map { |entry| entry.entryable.try(:category_id) }+ .tally+ .max_by { |_category_id, count| count }+ &.first+ end+ end+enddiff --git a/app/models/recurring_transaction/cleaner.rb b/app/models/recurring_transaction/cleaner.rbindex ec5dfd9172..5a0da14323 100644--- a/app/models/recurring_transaction/cleaner.rb+++ b/app/models/recurring_transaction/cleaner.rb@@ -1,4 +1,6 @@class RecurringTransaction+ # Bills subsystem: staleness is measured in the series' own cycles, so+ # quarterly and annual bills survive the gaps between normal occurrences.class Cleanerattr_reader :family@@ -6,8 +8,10 @@ class RecurringTransaction@family = familyend- # Mark recurring transactions as inactive if they haven't occurred recently- # Uses 2 months for automatic recurring, 6 months for manual recurring.+ # Mark recurring transactions as inactive if they haven't occurred+ # recently, where "recently" is measured in the series' own cycles (see+ # RecurringTransaction#staleness_threshold_date) so quarterly and annual+ # bills survive the gaps between their perfectly normal occurrences.## Transfer rows (destination_account_id present) are included: as of issue# #1590, `matching_transactions` detects the Transfer pair, so a still-active@@ -21,10 +25,8 @@ class RecurringTransaction.find_each do |recurring_transaction|next unless recurring_transaction.should_be_inactive?- # Determine threshold based on manual flag- threshold = recurring_transaction.manual? ? 6.months.ago.to_date : 2.months.ago.to_date-# Double-check if there are any recent matching transactions+ threshold = recurring_transaction.staleness_threshold_daterecent_matches = recurring_transaction.matching_transactions.select { |entry| entry.date >= threshold }if recent_matches.empty?diff --git a/app/models/recurring_transaction/declared_bill.rb b/app/models/recurring_transaction/declared_bill.rbnew file mode 100644index 0000000000..03df89dd31--- /dev/null+++ b/app/models/recurring_transaction/declared_bill.rb@@ -0,0 +1,123 @@+class RecurringTransaction+ # The one declared-bill build path, shared by the add-bill form and the AI+ # create tool so the two can never drift on the rules that matter here:+ # the account must be one the user can actually reach, and the amount+ # carries the sign convention (income is stored negative).+ class DeclaredBill+ attr_reader :family, :user, :attrs++ def initialize(family:, user:, attrs:)+ @family = family+ @user = user+ @attrs = attrs+ end++ def build+ account = user.accessible_accounts.find_by(id: attrs[:account_id])+ due = begin+ Date.parse(attrs[:first_due_on].to_s)+ rescue Date::Error+ nil+ end++ is_income = ActiveModel::Type::Boolean.new.cast(attrs[:is_income]) || false+ # BigDecimal parses "Infinity" and "NaN" as non-finite numbers; both are+ # invalid here, same as unparseable input.+ amount = begin+ BigDecimal(attrs[:amount].to_s.presence || "0").abs+ rescue ArgumentError+ nil+ end+ # update_bill rejects zero outright, and the schema says minimum 0.01, but+ # strict mode is off so nothing enforced it here: a zero bill was written+ # happily, and its cycles can never close because close_worthy? asks for a+ # positive expected amount, so it sat open and overdue forever.+ amount = nil if amount && (!amount.finite? || amount.zero?)+ amount = -amount if amount && is_income++ recurring = family.recurring_transactions.new(+ name: attrs[:name],+ amount: amount,+ bill_type: is_income ? "income" : "bill",+ account: account,+ currency: account&.currency || family.currency,+ payment_url: attrs[:payment_url],+ autopay: ActiveModel::Type::Boolean.new.cast(attrs[:autopay]) || false,+ notes: attrs[:notes],+ status: "active",+ manual: true,+ occurrence_count: 0+ )+ recurring.frequency_preset = attrs[:frequency_preset]+ recurring.first_due_on = attrs[:first_due_on]++ if amount.nil?+ recurring.errors.add(:base, I18n.t("recurring_transactions.create.amount_invalid"))+ return recurring+ end++ if due.nil?+ recurring.errors.add(:base, I18n.t("recurring_transactions.create.due_date_required"))+ return recurring+ end++ recurring.expected_day_of_month = due.day+ recurring.anchor_date = due+ recurring.last_occurrence_date = due+ recurring.next_expected_date = due++ FrequencyPreset.apply(+ recurring,+ preset: attrs[:frequency_preset],+ day_of_month: due.day,+ weekday: due.wday,+ month_of_year: due.month+ )++ recurring+ end++ # A series for this identifier may already exist; a second legitimate one+ # (another tier from the same biller) is distinguished by its amount, so+ # the amount is stamped into dedup_scope before the first insert. The same+ # identity at the same amount then collides immediately and is reported as+ # a validation error rather than an escaping exception.+ def self.save(recurring)+ recurring.dedup_scope = recurring.amount.to_d.to_s("F") if recurring.dedup_scope.blank?++ # Every dedup index is keyed on account_id, and Postgres treats NULLs as+ # distinct, so a bill created without an account collides with nothing.+ # Declaring one is explicitly supported ("omit it to create the bill+ # without an account"), which meant a retried create silently doubled the+ # family's recurring commitments. No partial index can express this, so+ # the check lives here.+ if recurring.account_id.nil? && account_less_duplicate?(recurring)+ recurring.errors.add(:base, I18n.t("recurring_transactions.create.already_exists"))+ return false+ end++ recurring.save+ rescue ActiveRecord::RecordNotUnique+ recurring.errors.add(:base, I18n.t("recurring_transactions.create.already_exists"))+ false+ end++ # Mirrors the identity the unique indexes use, minus the account that is+ # absent by definition: a merchant-keyed row matches on merchant, a+ # name-keyed row matches on name.+ def self.account_less_duplicate?(recurring)+ scope = recurring.family.recurring_transactions+ .where(account_id: nil,+ currency: recurring.currency,+ dedup_scope: recurring.dedup_scope,+ destination_account_id: recurring.destination_account_id)+ scope = scope.where.not(id: recurring.id) if recurring.id++ if recurring.merchant_id.present?+ scope.exists?(merchant_id: recurring.merchant_id)+ else+ scope.exists?(name: recurring.name, merchant_id: nil)+ end+ end+ end+enddiff --git a/app/models/recurring_transaction/frequency_preset.rb b/app/models/recurring_transaction/frequency_preset.rbnew file mode 100644index 0000000000..36df1901f8--- /dev/null+++ b/app/models/recurring_transaction/frequency_preset.rb@@ -0,0 +1,210 @@+class RecurringTransaction+ # Translates between the frequency picker's presets and recurrence_rules+ # rows. A preset is a named rule shape (biweekly = one weekly rule with+ # interval 2); anything the picker cannot express reads back as CUSTOM and+ # is left untouched.+ class FrequencyPreset+ PRESETS = %w[monthly weekly biweekly semimonthly quarterly semiannual annual].freeze+ CUSTOM = "custom"++ Detection = Data.define(:key, :day_of_month, :second_day_of_month, :weekday, :month_of_year)++ class << self+ # Reads the series' rules back into picker values. Zero rules is the+ # legacy implicit monthly.+ def detect(recurring)+ rules = live_rules(recurring)++ case+ when rules.empty?+ detection(key: "monthly", day_of_month: recurring.expected_day_of_month)+ when rules.size == 1+ detect_single(rules.first)+ when rules.size == 2 && rules.all? { |rule| monthly_day_rule?(rule) }+ days = canonical_semimonthly_days(rules.map(&:day_of_month))+ if days.uniq.size == 1+ detection(key: "monthly", day_of_month: days.first)+ else+ detection(key: "semimonthly", day_of_month: days.first, second_day_of_month: days.last)+ end+ else+ detection(key: CUSTOM)+ end+ end++ # Replaces the series' rules with the preset's shape. Assigns only, so the+ # caller's save persists atomically and invalid input surfaces as normal+ # validation errors. An unchanged cadence is a no-op.+ #+ # Returns true only when it actually rewrote the cadence, so a caller can+ # tell a deliberate schedule change from an unrelated edit.+ def apply(recurring, preset:, day_of_month: nil, second_day_of_month: nil, weekday: nil, month_of_year: nil)+ return false if preset.blank? || preset == CUSTOM+ return false unless PRESETS.include?(preset)++ reference = recurring.anchor_date || recurring.last_occurrence_date || Date.current+ target = target_detection(recurring, reference, preset,+ day_of_month: presence_int(day_of_month),+ second_day_of_month: presence_int(second_day_of_month),+ weekday: presence_int(weekday),+ month_of_year: presence_int(month_of_year))+ return false if target == detect(recurring)++ write(recurring, target, reference)+ true+ end++ # Human-readable cadence, e.g. "Every 2 weeks on Friday".+ def label(recurring)+ found = detect(recurring)++ case found.key+ when "monthly"+ I18n.t("recurring_transactions.frequency.monthly", day: day_phrase(found.day_of_month))+ when "weekly"+ I18n.t("recurring_transactions.frequency.weekly", weekday: weekday_name(found.weekday))+ when "biweekly"+ I18n.t("recurring_transactions.frequency.biweekly", weekday: weekday_name(found.weekday))+ when "semimonthly"+ I18n.t("recurring_transactions.frequency.semimonthly",+ first: day_phrase(found.day_of_month), second: day_phrase(found.second_day_of_month))+ when "quarterly"+ I18n.t("recurring_transactions.frequency.quarterly", day: day_phrase(found.day_of_month))+ when "semiannual"+ I18n.t("recurring_transactions.frequency.semiannual", day: day_phrase(found.day_of_month))+ when "annual"+ I18n.t("recurring_transactions.frequency.annual",+ month: I18n.t("date.month_names")[found.month_of_year], day: day_phrase(found.day_of_month))+ else+ I18n.t("recurring_transactions.frequency.custom")+ end+ end++ private+ def detection(key:, day_of_month: nil, second_day_of_month: nil, weekday: nil, month_of_year: nil)+ Detection.new(key:, day_of_month:, second_day_of_month:, weekday:, month_of_year:)+ end++ def detect_single(rule)+ case rule.frequency+ when "weekly"+ case rule.interval+ when 1 then detection(key: "weekly", weekday: rule.weekday)+ when 2 then detection(key: "biweekly", weekday: rule.weekday)+ else detection(key: CUSTOM)+ end+ when "monthly"+ return detection(key: CUSTOM) unless rule.day_of_month.present?++ case rule.interval+ when 1 then detection(key: "monthly", day_of_month: rule.day_of_month)+ when 3 then detection(key: "quarterly", day_of_month: rule.day_of_month)+ when 6 then detection(key: "semiannual", day_of_month: rule.day_of_month)+ else detection(key: CUSTOM)+ end+ when "yearly"+ if rule.interval == 1 && rule.day_of_month.present?+ detection(key: "annual", day_of_month: rule.day_of_month, month_of_year: rule.month_of_year)+ else+ detection(key: CUSTOM)+ end+ end+ end++ def live_rules(recurring)+ recurring.recurrence_rules.reject(&:marked_for_destruction?)+ end++ # The Detection the submitted form values resolve to, with the same+ # defaulting write() will use, so equality against detect() is exact.+ def target_detection(recurring, reference, preset, day_of_month:, second_day_of_month:, weekday:, month_of_year:)+ case preset+ when "monthly", "quarterly", "semiannual"+ detection(key: preset, day_of_month: day_of_month || recurring.expected_day_of_month)+ when "weekly", "biweekly"+ detection(key: preset, weekday: weekday)+ when "semimonthly"+ days = canonical_semimonthly_days([ day_of_month || 1, second_day_of_month || 15 ])+ if days.uniq.size == 1+ detection(key: "monthly", day_of_month: days.first)+ else+ detection(key: preset, day_of_month: days.first, second_day_of_month: days.last)+ end+ when "annual"+ detection(key: preset, day_of_month: day_of_month || reference.day,+ month_of_year: month_of_year || reference.month)+ end+ end++ def write(recurring, target, reference)+ recurring.rules_rewritten = true+ recurring.recurrence_rules.each(&:mark_for_destruction)++ case target.key+ when "monthly"+ build_rule(recurring, frequency: "monthly", day_of_month: target.day_of_month)+ when "weekly"+ build_rule(recurring, frequency: "weekly", weekday: target.weekday)+ when "biweekly"+ recurring.anchor_date ||= reference+ build_rule(recurring, frequency: "weekly", weekday: target.weekday, interval: 2)+ when "semimonthly"+ build_rule(recurring, frequency: "monthly", day_of_month: target.day_of_month)+ build_rule(recurring, frequency: "monthly", day_of_month: target.second_day_of_month, position: 1)+ when "quarterly"+ recurring.anchor_date ||= reference+ build_rule(recurring, frequency: "monthly", day_of_month: target.day_of_month, interval: 3)+ when "semiannual"+ recurring.anchor_date ||= reference+ build_rule(recurring, frequency: "monthly", day_of_month: target.day_of_month, interval: 6)+ when "annual"+ build_rule(recurring, frequency: "yearly", day_of_month: target.day_of_month,+ month_of_year: target.month_of_year)+ end++ recurring.expected_day_of_month = authoritative_day(target.key, target.day_of_month, reference)+ end++ # LAST sorts as the day it stands for, the end of the month, so+ # (15, LAST) and (LAST, 15) are one schedule. Without one canonical+ # order each reapply rewrote the rules instead of no-opping. Two equal+ # anchors are one monthly schedule, not a semimonthly pair.+ def canonical_semimonthly_days(days)+ days.sort_by { |day| day == RecurrenceRule::LAST ? 32 : day }+ end++ def monthly_day_rule?(rule)+ rule.frequency == "monthly" && rule.interval == 1 && rule.day_of_month.present?+ end++ def build_rule(recurring, position: 0, **attrs)+ recurring.recurrence_rules.build(position: position, **attrs)+ end++ # expected_day_of_month stays NOT NULL and authoritative for monthly+ # cadences; other cadences populate it but do not schedule from it.+ def authoritative_day(preset, day, reference)+ case preset+ when "monthly", "semimonthly", "quarterly", "semiannual", "annual"+ day == RecurrenceRule::LAST ? 31 : day+ else+ reference.day+ end+ end++ def presence_int(value)+ value.present? ? value.to_i : nil+ end++ def day_phrase(day)+ return I18n.t("recurring_transactions.frequency.last_day") if day == RecurrenceRule::LAST++ day.ordinalize+ end++ def weekday_name(weekday)+ I18n.t("date.day_names")[weekday]+ end+ end+ end+enddiff --git a/app/models/recurring_transaction/history_backfiller.rb b/app/models/recurring_transaction/history_backfiller.rbnew file mode 100644index 0000000000..a82056fc9e--- /dev/null+++ b/app/models/recurring_transaction/history_backfiller.rb@@ -0,0 +1,57 @@+class RecurringTransaction+ # Reconstructs past occurrence history and reconciles it against real+ # entries. Re-runnable by construction: generation upserts, matching writes+ # only unambiguous exact-tier links against entries not already allocated,+ # and the prune only deletes open, unallocated rows.+ class HistoryBackfiller+ attr_reader :family, :months++ def initialize(family, months: 6, series_scope: nil)+ @family = family+ @months = months+ @series_scope = series_scope+ end++ # Returns the number of pruned occurrences.+ def run!+ from = months.months.ago.to_date++ series_scope.find_each do |series|+ OccurrenceGenerator.new(series).backfill!(from: from)+ end++ # Family-wide even when series_scope narrows generation: exact-tier+ # matching is idempotent and only ever closes history a real entry+ # anchors, so the wider pass is safe and keeps one Matcher entry point.+ Matcher.new(family).run_backfill!++ prune_uncovered_past!+ end++ private++ def series_scope+ @series_scope || family.recurring_transactions.active+ end++ # Uncovered past occurrences (before the current cycle, no payments)+ # are deleted, not marked missed -- backfill reconstructs what+ # happened, it does not fabricate debt.+ def prune_uncovered_past!+ pruned = 0++ series_scope.find_each do |series|+ cycle_start = series.schedule.cycle_for(Date.current)&.begin+ next if cycle_start.nil?++ pruned += series.recurring_occurrences+ .open_status+ .where("due_on < ?", cycle_start)+ .where.not(id: RecurringAllocation.select(:recurring_occurrence_id))+ .delete_all+ end++ pruned+ end+ end+enddiff --git a/app/models/recurring_transaction/identifier.rb b/app/models/recurring_transaction/identifier.rbindex 03a49dea35..54c0e487cc 100644--- a/app/models/recurring_transaction/identifier.rb+++ b/app/models/recurring_transaction/identifier.rb@@ -1,4 +1,8 @@class RecurringTransaction+ # Bills subsystem: detection now clusters amounts within a tolerance rather+ # than requiring an exact match, claims existing series instead of duplicating+ # them, lands unclaimed patterns as `suggested`, and offers candidate patterns+ # to the add-bill pickers.class Identifierattr_reader :family@@ -6,146 +10,121 @@ class RecurringTransaction@family = familyend- # Identify and create/update recurring transactions for the family- def identify_recurring_patterns- three_months_ago = 3.months.ago.to_date+ # Amounts within this percentage of a cluster's running mean belong to the+ # same obligation, so a price creep stays one series instead of forking a+ # new row per price. Mirrors the recurring_transactions.amount_tolerance_pct+ # column default.+ DEFAULT_TOLERANCE_PCT = 7.5++ # Sub-dollar patterns (penny vault transfers, rounding sweeps) are never+ # worth offering as a bill or income starting point.+ MINIMUM_CANDIDATE_AMOUNT = 1++ # Read-only: recurring-shaped patterns NOT already covered by an+ # existing series, for the add-dialog picker. Two consistent+ # occurrences are enough to OFFER a candidate (the automatic pipeline+ # keeps requiring three to act on its own).+ def candidate_patterns(sign: :outflow, min_occurrences: 2)+ wanted_negative = sign == :inflow+ existing_by_identity = family.recurring_transactions.to_a.group_by { |recurring| identity_key(recurring) }++ collect_patterns(min_occurrences: min_occurrences).select do |pattern|+ next false unless pattern[:amount].negative? == wanted_negative+ next false if pattern[:expected_amount_avg].abs < MINIMUM_CANDIDATE_AMOUNT++ identity = [ pattern[:merchant_id] ? [ :merchant, pattern[:merchant_id] ] : [ :name, pattern[:name] ],+ pattern[:currency], pattern[:account_id], nil ]+ candidates = existing_by_identity[identity] || []+ nearest_within_tolerance(candidates, pattern[:expected_amount_avg]).nil?+ end+ end++ # Income candidates are source-based, not amount-clustered: a variable+ # paycheck (weekly hours) never forms an amount cluster and rarely+ # lands on the same day of the month, but several deposits from one+ # source inside the lookback is exactly what a payday source looks+ # like. Bills keep the stricter pattern shape via candidate_patterns.+ def income_source_candidates(lookback: 90.days, min_occurrences: 2)+ declared_income = family.recurring_transactions.where(bill_type: "income").to_a- # Skip transfer-kind transactions: they're one half of a Transfer pair, so grouping them- # under their single account would produce incoherent recurring "patterns" that don't- # represent the underlying account-pair flow. Recurring transfers are tracked on a- # different shape (RecurringTransaction with destination_account_id). Filtering at the- # SQL level avoids loading and discarding transfer entries for a busy family.- entries_with_transactions = family.entries+ inflows = family.entries.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id").where(entryable_type: "Transaction")- .where("entries.date >= ?", three_months_ago)+ .where("entries.date >= ?", lookback.ago.to_date)+ .where("entries.amount < 0").where.not("transactions.kind": Transaction::TRANSFER_KINDS).includes(:entryable).to_a- # Group by merchant (if present) or name, along with amount (preserve sign) and currency.- grouped_transactions = entries_with_transactions- .select { |entry| entry.entryable.is_a?(Transaction) }+ inflows.group_by do |entry|transaction = entry.entryable- # Use merchant_id if present, otherwise use entry nameidentifier = transaction.merchant_id.present? ? [ :merchant, transaction.merchant_id ] : [ :name, entry.name ]- [ identifier, entry.amount.round(2), entry.currency, entry.account_id ]+ [ identifier, entry.currency, entry.account_id ]end+ .filter_map do |(identifier, currency, account_id), group|+ next if group.size < min_occurrences- recurring_patterns = []-- grouped_transactions.each do |(identifier, amount, currency, account_id), entries|- next if entries.size < 3 # Must have at least 3 occurrences+ amounts = group.map { |entry| entry.amount.abs }+ next if (amounts.sum / amounts.size) < MINIMUM_CANDIDATE_AMOUNT+ next if claimed_income_source?(declared_income, identifier, currency, account_id)- # Check if the last occurrence was within the last 45 days- last_occurrence = entries.max_by(&:date)- next if last_occurrence.date < 45.days.ago.to_date+ last_occurrence = group.max_by(&:date)- # Check if transactions occur on similar days (within 5 days of each other)- days_of_month = entries.map { |e| e.date.day }.sort-- # Calculate if days cluster together (standard deviation check)- if days_cluster_together?(days_of_month)- expected_day = calculate_expected_day(days_of_month)-- # Unpack identifier - either [:merchant, id] or [:name, name_string]- identifier_type, identifier_value = identifier-- pattern = {- amount: amount,+ {+ name: identifier.first == :name ? identifier.last : nil,+ merchant_id: identifier.first == :merchant ? identifier.last : nil,currency: currency,account_id: account_id,- expected_day_of_month: expected_day,+ amount: last_occurrence.amount,+ expected_amount_avg: -(amounts.sum / amounts.size),last_occurrence_date: last_occurrence.date,- occurrence_count: entries.size,- entries: entries+ occurrence_count: group.size,+ entries: group}-- if identifier_type == :merchant- pattern[:merchant_id] = identifier_value- else- pattern[:name] = identifier_value- end-- recurring_patterns << patternend- end+ .sort_by { |candidate| -candidate[:entries].sum { |entry| entry.amount.abs } }+ end- # Create or update RecurringTransaction records. Load existing rows once- # so a busy family does not issue one lookup per detected pattern.- existing_recurring_transactions_by_key = family.recurring_transactions- .to_a- .index_by { |recurring| recurring_transaction_lookup_key(recurring) }+ # Identify and create/update recurring transactions for the family+ def identify_recurring_patterns+ three_months_ago = 3.months.ago.to_date+ recurring_patterns = collect_patterns(min_occurrences: 3)- recurring_patterns.each do |pattern|- # Build find conditions based on whether it's merchant-based or name-based- find_conditions = {- amount: pattern[:amount],- currency: pattern[:currency],- account_id: pattern[:account_id]- }+ # Claim-or-create. Existing rows are grouped by identity (merchant or+ # name, currency, account) and each pattern claims the nearest existing+ # series whose amount sits within tolerance -- INCLUDING manual and+ # ended rows, so detection can never recreate a bill the user already+ # declared by hand or dismissed. Only an unclaimed pattern creates a+ # row, and it lands as `suggested`, awaiting confirmation.+ existing_by_identity = family.recurring_transactions.to_a.group_by { |recurring| identity_key(recurring) }- if pattern[:merchant_id].present?- find_conditions[:merchant_id] = pattern[:merchant_id]- find_conditions[:name] = nil- else- find_conditions[:name] = pattern[:name]- find_conditions[:merchant_id] = nil+ recurring_patterns.each do |pattern|+ identity = [ pattern[:merchant_id] ? [ :merchant, pattern[:merchant_id] ] : [ :name, pattern[:name] ],+ pattern[:currency], pattern[:account_id], nil ]+ candidates = existing_by_identity[identity] || []+ claimed = nearest_within_tolerance(candidates, pattern[:expected_amount_avg])++ if claimed+ # Manual rows are refreshed by the dedicated variance pass; ended+ # rows are tombstones (the user dismissed or cancelled the bill).+ next if claimed.manual? || claimed.ended?++ update_claimed_series(claimed, pattern)+ nextendbegin- lookup_key = recurring_transaction_lookup_key(find_conditions)- recurring_transaction = existing_recurring_transactions_by_key[lookup_key] ||- family.recurring_transactions.build(find_conditions)-- # Handle manual recurring transactions specially- if recurring_transaction.persisted? && recurring_transaction.manual?- # Manual recurring variance is recalculated once in the batch pass- # after automatic pattern updates finish.- next- end-- # Set the name or merchant_id on new records- if recurring_transaction.new_record?- if pattern[:merchant_id].present?- recurring_transaction.merchant_id = pattern[:merchant_id]- else- recurring_transaction.name = pattern[:name]- end- # New auto-detected recurring transactions are not manual- recurring_transaction.manual = false- end-- recurring_transaction.assign_attributes(- expected_day_of_month: pattern[:expected_day_of_month],- last_occurrence_date: pattern[:last_occurrence_date],- next_expected_date: calculate_next_expected_date(pattern[:last_occurrence_date], pattern[:expected_day_of_month]),- occurrence_count: pattern[:occurrence_count],- status: recurring_transaction.new_record? ? "active" : recurring_transaction.status- )-- recurring_transaction.save!- existing_recurring_transactions_by_key[lookup_key] = recurring_transaction+ created = create_suggested_series(pattern, scoped: candidates.any?)+ (existing_by_identity[identity] ||= []) << createdrescue ActiveRecord::RecordNotUnique- # Race condition: another process created the same record between find and save.- # Retry with find to get the existing record and update it.- recurring_transaction = family.recurring_transactions.find_by(find_conditions)- next unless recurring_transaction-- # Skip manual recurring transactions- if recurring_transaction.manual?- # Manual recurring variance is recalculated once in the batch pass- # after automatic pattern updates finish.- next- end+ # Race: another process created the same identity between load and+ # save. Re-read and treat it as the claimed series.+ racer = family.recurring_transactions.find_by(identity_conditions(pattern, scoped: candidates.any?))+ next unless racer+ next if racer.manual? || racer.ended?- recurring_transaction.update!(- expected_day_of_month: pattern[:expected_day_of_month],- last_occurrence_date: pattern[:last_occurrence_date],- next_expected_date: calculate_next_expected_date(pattern[:last_occurrence_date], pattern[:expected_day_of_month]),- occurrence_count: pattern[:occurrence_count]- )+ update_claimed_series(racer, pattern)endend@@ -182,32 +161,239 @@ class RecurringTransactionlast_entry = matching_entries.max_by(&:date)# Recalculate variance from all occurrences (including identical amounts)+ # The series' own schedule computes the next date so a manual row+ # with weekly or other non-monthly rules advances on its real+ # cadence; legacy monthly rows keep byte-identical behavior.recurring.update!(expected_amount_min: matching_amounts.min,expected_amount_max: matching_amounts.max,expected_amount_avg: matching_amounts.sum / matching_amounts.size,occurrence_count: matching_amounts.size,last_occurrence_date: last_entry.date,- next_expected_date: calculate_next_expected_date(last_entry.date, recurring.expected_day_of_month)+ next_expected_date: recurring.schedule.next_occurrence_after(last_entry.date))endendprivate- def recurring_transaction_lookup_key(recurring_or_attributes)- # Keep this aligned with the non-transfer recurring transaction unique- # indexes. Automatic recurring rows are amount-scoped; variable manual- # amounts are tracked separately in expected_amount_*.- amount = recurring_or_attributes.respond_to?(:amount) ? recurring_or_attributes.amount : recurring_or_attributes[:amount]- currency = recurring_or_attributes.respond_to?(:currency) ? recurring_or_attributes.currency : recurring_or_attributes[:currency]- account_id = recurring_or_attributes.respond_to?(:account_id) ? recurring_or_attributes.account_id : recurring_or_attributes[:account_id]- merchant_id = recurring_or_attributes.respond_to?(:merchant_id) ? recurring_or_attributes.merchant_id : recurring_or_attributes[:merchant_id]- name = recurring_or_attributes.respond_to?(:name) ? recurring_or_attributes.name : recurring_or_attributes[:name]-- identifier_type = merchant_id.present? ? :merchant : :name- identifier_value = merchant_id.presence || name-- [ amount, currency, account_id, identifier_type, identifier_value ]+ # Identity as the unique indexes see it, minus dedup_scope: several+ # series can legitimately share this key (subscription tiers), which is+ # exactly why claiming goes through amount-nearness rather than lookup.+ def identity_key(recurring)+ identifier = recurring.merchant_id.present? ? [ :merchant, recurring.merchant_id ] : [ :name, recurring.name ]+ [ identifier, recurring.currency, recurring.account_id, recurring.destination_account_id ]+ end++ # Shared pattern collection: groups three months of non-transfer+ # entries by identity, clusters amounts within tolerance, and keeps+ # clusters that recur on a consistent day. The caller decides how many+ # occurrences constitute a pattern.+ def collect_patterns(min_occurrences:)+ three_months_ago = 3.months.ago.to_date++ # Skip transfer-kind transactions: they're one half of a Transfer pair, so grouping them+ # under their single account would produce incoherent recurring "patterns" that don't+ # represent the underlying account-pair flow. Recurring transfers are tracked on a+ # different shape (RecurringTransaction with destination_account_id). Filtering at the+ # SQL level avoids loading and discarding transfer entries for a busy family.+ entries_with_transactions = family.entries+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id")+ .where(entryable_type: "Transaction")+ .where("entries.date >= ?", three_months_ago)+ .where.not("transactions.kind": Transaction::TRANSFER_KINDS)+ .includes(:entryable)+ .to_a++ # Group by merchant (if present) or name, plus currency and account --+ # deliberately NOT by amount. Amounts are clustered within tolerance+ # inside each group, so three subscription tiers to one merchant remain+ # three patterns while a price creep stays one.+ grouped_transactions = entries_with_transactions+ .select { |entry| entry.entryable.is_a?(Transaction) }+ .group_by do |entry|+ transaction = entry.entryable+ identifier = transaction.merchant_id.present? ? [ :merchant, transaction.merchant_id ] : [ :name, entry.name ]+ [ identifier, entry.currency, entry.account_id ]+ end++ patterns = []++ grouped_transactions.each do |(identifier, currency, account_id), entries|+ cluster_by_amount(entries).each do |cluster|+ next if cluster.size < min_occurrences++ # Check if the last occurrence was within the last 45 days+ last_occurrence = cluster.max_by(&:date)+ next if last_occurrence.date < 45.days.ago.to_date++ # Check if transactions occur on similar days (within 5 days of each other)+ days_of_month = cluster.map { |e| e.date.day }.sort+ next unless days_cluster_together?(days_of_month)++ amounts = cluster.map(&:amount)+ identifier_type, identifier_value = identifier++ pattern = {+ # The most recent charge is the current price; the cluster's+ # spread is recorded as the variance band.+ amount: last_occurrence.amount,+ expected_amount_min: amounts.min,+ expected_amount_max: amounts.max,+ expected_amount_avg: amounts.sum / amounts.size,+ currency: currency,+ account_id: account_id,+ expected_day_of_month: calculate_expected_day(days_of_month),+ last_occurrence_date: last_occurrence.date,+ occurrence_count: cluster.size,+ entries: cluster+ }++ if identifier_type == :merchant+ pattern[:merchant_id] = identifier_value+ else+ pattern[:name] = identifier_value+ end++ patterns << pattern+ end+ end++ patterns+ end++ # Splits a group's entries into amount clusters: sorted by amount, an+ # entry joins the current cluster while it sits within tolerance of the+ # cluster's running mean, else starts a new one. Comparing against the+ # mean (not the neighbor) stops a chain of small steps from drifting one+ # cluster across genuinely different prices.+ def cluster_by_amount(entries)+ clusters = []++ entries.sort_by(&:amount).each do |entry|+ current = clusters.last++ if current && within_tolerance?(cluster_mean(current), entry.amount)+ current << entry+ else+ clusters << [ entry ]+ end+ end++ clusters+ end++ def cluster_mean(cluster)+ cluster.sum(&:amount) / cluster.size+ end++ def within_tolerance?(reference, amount)+ (amount - reference).abs <= reference.abs * (DEFAULT_TOLERANCE_PCT / 100.0)+ end++ # A payday source is claimed by ANY declared income series sharing its+ # identity, regardless of amount: variable pay means amount-nearness is+ # meaningless for income.+ def claimed_income_source?(declared_income, identifier, currency, account_id)+ identifier_type, identifier_value = identifier++ declared_income.any? do |recurring|+ next false unless recurring.currency == currency+ next false if recurring.account_id.present? && recurring.account_id != account_id++ if identifier_type == :merchant+ recurring.merchant_id == identifier_value+ else+ recurring.merchant_id.nil? && recurring.name == identifier_value+ end+ end+ end++ def nearest_within_tolerance(candidates, target_amount)+ candidates+ .select { |recurring| within_tolerance?(target_amount, recurring.amount) }+ .min_by { |recurring| (recurring.amount - target_amount).abs }+ end++ # Refreshes a claimed series' cadence bookkeeping and variance band.+ # Amount and status are left alone (price changes belong to+ # PriceChangeDetector), and so is the due day once the user has pinned+ # the schedule.+ def update_claimed_series(recurring, pattern)+ # A detected day shift lands before the date math, so the persisted+ # next_expected_date agrees with the regenerated occurrences instead+ # of keeping the old day for a cycle.+ recurring.last_occurrence_date = pattern[:last_occurrence_date]+ unless recurring.schedule_pinned?+ recurring.expected_day_of_month = pattern[:expected_day_of_month]+ sync_monthly_rule_day(recurring, pattern[:expected_day_of_month])+ end++ recurring.update!(+ last_occurrence_date: pattern[:last_occurrence_date],+ next_expected_date: recurring.schedule.next_occurrence_after(pattern[:last_occurrence_date]),+ occurrence_count: pattern[:occurrence_count],+ expected_amount_min: pattern[:expected_amount_min],+ expected_amount_max: pattern[:expected_amount_max],+ expected_amount_avg: pattern[:expected_amount_avg]+ )+ end++ # Scheduling reads recurrence_rules, not expected_day_of_month, so a+ # detected day shift must move the rule and regenerate future occurrences.+ def sync_monthly_rule_day(recurring, day)+ rules = recurring.recurrence_rules+ return unless rules.size == 1++ rule = rules.first+ return unless rule.frequency == "monthly" && rule.interval == 1+ return if rule.day_of_month.blank? || rule.day_of_month == RecurrenceRule::LAST+ return if rule.day_of_month == day++ rule.update!(day_of_month: day)+ # When the day column itself is about to change, the model's own+ # after_commit regenerates once on save. The explicit pass is only+ # for a rule that drifted out of agreement with an unchanged column.+ OccurrenceGenerator.new(recurring).regenerate_future! unless recurring.will_save_change_to_expected_day_of_month?+ end++ def create_suggested_series(pattern, scoped:)+ account = pattern[:account_id] && Account.find_by(id: pattern[:account_id])+ classification = Classifier.classify(+ name: pattern[:name] || pattern[:entries].first.name,+ entries: pattern[:entries],+ account: account+ )+ income = pattern[:amount].negative?++ family.recurring_transactions.create!(+ identity_conditions(pattern, scoped: scoped).merge(+ amount: pattern[:amount],+ expected_amount_min: pattern[:expected_amount_min],+ expected_amount_max: pattern[:expected_amount_max],+ expected_amount_avg: pattern[:expected_amount_avg],+ expected_day_of_month: pattern[:expected_day_of_month],+ last_occurrence_date: pattern[:last_occurrence_date],+ next_expected_date: calculate_next_expected_date(pattern[:last_occurrence_date], pattern[:expected_day_of_month]),+ occurrence_count: pattern[:occurrence_count],+ status: "suggested",+ bill_type: income ? "income" : classification.bill_type,+ category_id: income ? nil : classification.category_id,+ autopay: income ? false : classification.autopay,+ manual: false+ )+ )+ end++ # A second series for an already-taken identity is distinguished by+ # stamping the cluster's mean amount into dedup_scope.+ def identity_conditions(pattern, scoped:)+ {+ currency: pattern[:currency],+ account_id: pattern[:account_id],+ merchant_id: pattern[:merchant_id],+ name: pattern[:merchant_id].present? ? nil : pattern[:name],+ dedup_scope: scoped ? pattern[:expected_amount_avg].round(2).to_s("F") : ""+ }enddef matching_entries_by_manual_recurring_id(recurring_transactions, lookback_months:)@@ -250,10 +436,7 @@ class RecurringTransaction# happen to share a merchant/day don't get averaged in (issue #2936# follow-up).return false unless RecurringTransaction.amount_within_variance_band?(entry.amount, recurring.amount)-- expected_day = [ recurring.expected_day_of_month, entry.date.end_of_month.day ].min- day = entry.date.day- return false if circular_distance(day, expected_day) > 2+ return false unless recurring.schedule.matches_day?(entry.date)if recurring.merchant_id.present?entry.read_attribute("transaction_merchant_id") == recurring.merchant_id@@ -262,34 +445,28 @@ class RecurringTransactionendend- # Check if days cluster together (within ~5 days variance)- # Uses circular distance to handle month-boundary wrapping (e.g., 28, 29, 30, 31, 1, 2)+ # A recurring charge lands on the SAME day each month: every occurrence+ # must sit within the matching tolerance (2 days) of the expected day+ # on the circular calendar. Circular distance is what handles short+ # months -- a day-30 bill's February charge on the 28th is 2 away, in.+ #+ # This replaced a standard-deviation test that averaged the drift and+ # so accepted charges scattered across the 5th, 10th and 15th as one+ # "recurring" pattern. Consistency is per-occurrence, not on average,+ # and detection now agrees with the matcher about what "the same+ # occurrence" means.def days_cluster_together?(days)return false if days.empty?- # Calculate median as reference point- median = calculate_expected_day(days)-- # Calculate circular distances from median- circular_distances = days.map { |day| circular_distance(day, median) }-- # Calculate standard deviation of circular distances- mean_distance = circular_distances.sum.to_f / circular_distances.size- variance = circular_distances.map { |dist| (dist - mean_distance)**2 }.sum / circular_distances.size- std_dev = Math.sqrt(variance)+ expected = calculate_expected_day(days)- # Allow up to 5 days standard deviation- std_dev <= 5+ days.all? { |day| circular_distance(day, expected) <= Schedule::DAY_MATCH_TOLERANCE }end- # Calculate circular distance between two days on a 31-day circle- # Examples:- # circular_distance(1, 31) = 2 (wraps around: 31 -> 1 is 1 day forward)- # circular_distance(28, 2) = 5 (wraps: 28, 29, 30, 31, 1, 2)+ # Circular day distance is owned by Schedule; kept as a private alias+ # for the clustering math above.def circular_distance(day1, day2)- linear_distance = (day1 - day2).abs- wrap_distance = 31 - linear_distance- [ linear_distance, wrap_distance ].min+ Schedule.circular_day_distance(day1, day2)end# Calculate the expected day based on the most common day@@ -333,16 +510,9 @@ class RecurringTransactionoriginal_dayend- # Calculate next expected date+ # Calculate next expected date. Date math is owned by Schedule.def calculate_next_expected_date(last_date, expected_day)- next_month = last_date.next_month-- begin- Date.new(next_month.year, next_month.month, expected_day)- rescue ArgumentError- # If day doesn't exist in month, use last day of month- next_month.end_of_month- end+ Schedule.new(expected_day_of_month: expected_day).next_occurrence_after(last_date)endendenddiff --git a/app/models/recurring_transaction/matcher.rb b/app/models/recurring_transaction/matcher.rbnew file mode 100644index 0000000000..ebbaa9d2d3--- /dev/null+++ b/app/models/recurring_transaction/matcher.rb@@ -0,0 +1,392 @@+class RecurringTransaction+ # Scores candidate entries against a family's open occurrences and writes+ # allocations through the Allocator: confirmed at the exact tier, suggested+ # at the high tier, nothing below. Every signal behind a score is stored on+ # the allocation so the user can see why something matched.+ #+ # Conservative by design: auto-linking needs both a high score and an+ # unambiguous winner, user corrections are permanently sticky, and a pending+ # entry is never auto-linked.+ class Matcher+ # Tier thresholds over a maximum score of ~1.0.+ EXACT_TIER = BigDecimal("0.85")+ HIGH_TIER = BigDecimal("0.60")++ # An exact-tier match only auto-links when it beats the entry's next-best+ # occurrence by this margin; anything closer is ambiguous and demotes to+ # a suggestion.+ AMBIGUITY_MARGIN = BigDecimal("0.15")++ # Learned tolerance never widens beyond this, whatever the user confirms.+ MAX_LEARNED_TOLERANCE_PCT = 25++ Candidate = Data.define(:occurrence, :entry, :confidence, :signals)++ attr_reader :family++ def self.normalize_name(name)+ name.to_s.downcase.gsub(/\s+/, " ").strip+ end++ def initialize(family)+ @family = family+ end++ # Live mode: exact tier auto-links, high tier lands in the review queue.+ def run!+ apply(collect_candidates, suggest: true)+ end++ # Backfill mode: only unambiguous exact-tier matches are written, as+ # confirmed history. Historical suggestions would bury the review queue.+ def run_backfill!+ apply(collect_candidates(include_closed_window: true), suggest: false)+ end++ # Re-attaches allocations whose entry was replaced under them: some+ # providers post a pending transaction as a new row and delete the old one,+ # nullifying the FK. Amount and date survive, so an exact re-match restores+ # the link.+ def repair_orphans!+ orphans = RecurringAllocation+ .joins(:recurring_occurrence)+ .includes(recurring_occurrence: :recurring_transaction)+ .where(recurring_occurrences: { family_id: family.id })+ .where(entry_id: nil)+ .where(source: %w[auto_matched user_confirmed])++ orphans.find_each do |allocation|+ series = allocation.recurring_occurrence.recurring_transaction++ # Allocations store magnitudes, entries store signs: an income entry is+ # negative, so a magnitude-only lookup never found a reposted paycheck+ # and orphaned income stayed orphaned for good.+ amounts = [ allocation.source_amount, allocation.allocated_amount ].compact+ amounts = (amounts + amounts.map(&:-@)).uniq++ # Same date and amount alone can be a coincidental twin. The candidate+ # must also look like the series' own charge: the scoped account, the+ # merchant when both sides know one, and a related name otherwise. Not+ # the strict identity the live matcher uses, because a repost is the+ # one case where the descriptor legitimately mutates (POSTED suffixes,+ # PENDING prefixes), which is why this repair exists at all.+ replacement = family.entries+ .where(entryable_type: "Transaction")+ .where(currency: allocation.source_currency || allocation.currency)+ .where(date: allocation.paid_on)+ .where(amount: amounts)+ .where.not(id: RecurringAllocation.where.not(entry_id: nil).select(:entry_id))+ .then { |scope| series.account_id.present? ? scope.where(account_id: series.account_id) : scope }+ .includes(:entryable)+ .find { |entry| repair_identity?(series, entry) }++ allocation.update!(entry: replacement) if replacement+ end+ end++ # Scores one entry against one occurrence for a surface that shows a person+ # why something matches, so the picker and the auto-pipeline give the same+ # answer.+ #+ # nil means the entry could never belong to this series: a $6.44 charge from+ # another merchant is not a weak match, it is not a match at all.+ #+ # Read-only, so it is safe on a GET.+ Explanation = Data.define(:confidence, :signals)++ def explain(occurrence, entry)+ series = occurrence.recurring_transaction+ return nil unless identity_matches?(series, entry)+ return nil unless within_window?(occurrence, entry)++ confidence, signals = score(occurrence, series, entry)+ # A flat zero from `score` means the amount fell outside tolerance, and+ # that zero is the real gate: anything past the hard filters scores 0.65+.+ return nil unless confidence.positive?++ Explanation.new(confidence: confidence, signals: signals)+ end++ private+ def apply(candidates, suggest:)+ taken_entries = Set.new+ taken_occurrences = Set.new+ written = 0++ # Highest confidence claims first; each entry and occurrence is assigned+ # at most once per run. The id tiebreak only makes equally confident+ # candidates resolve deterministically, since sort_by is not stable.+ ordered = candidates.sort_by do |candidate|+ [ -candidate.confidence, candidate.occurrence.id, candidate.entry.id ]+ end++ ordered.each do |candidate|+ next if taken_entries.include?(candidate.entry.id)+ next if taken_occurrences.include?(candidate.occurrence.id)++ tier = tier_for(candidate, ordered)+ next if tier.nil?+ next if tier == :high && !suggest++ write_allocation(candidate, tier)+ taken_entries << candidate.entry.id+ taken_occurrences << candidate.occurrence.id+ written += 1+ end++ written+ end++ def tier_for(candidate, ordered)+ if candidate.confidence >= EXACT_TIER && !pending_entry?(candidate.entry) && unambiguous?(candidate, ordered)+ :exact+ elsif candidate.confidence >= HIGH_TIER+ # Suggestions render on the payment review queue, and income review+ # has no home there: a deposit either matches at the exact tier and+ # closes the payday, or waits.+ :high unless candidate.occurrence.recurring_transaction.typed_income?+ end+ end++ # A pending charge's amount can still change when it posts: suggested at+ # most, never auto-linked.+ def pending_entry?(entry)+ entry.entryable.respond_to?(:pending?) && entry.entryable.pending?+ end++ # Ambiguous when the entry scores nearly as well against another+ # occurrence: suggest rather than silently pick.+ def unambiguous?(candidate, ordered)+ runner_up = ordered.find do |other|+ other.entry.id == candidate.entry.id && other.occurrence.id != candidate.occurrence.id+ end++ runner_up.nil? || candidate.confidence - runner_up.confidence >= AMBIGUITY_MARGIN+ end++ def write_allocation(candidate, tier)+ occurrence = candidate.occurrence+ entry = candidate.entry++ Allocator.new(occurrence).allocate_matched!(+ entry: entry,+ state: tier == :exact ? "confirmed" : "suggested",+ confidence: candidate.confidence,+ signals: candidate.signals+ )+ rescue ActiveRecord::RecordNotUnique+ # Already allocated (a previous run wrote it); nothing to do.+ rescue Allocator::OverAllocationError+ # Another occurrence already claimed the entry's capacity. Skip the+ # candidate rather than aborting the run.+ end++ # The hard filters depend on the series and the entry, not the individual+ # occurrence, so they are asked once per series rather than once per cycle+ # the bill has ever had.+ def collect_candidates(include_closed_window: false)+ occurrences = open_occurrences+ return [] if occurrences.empty?++ rejected = rejected_pairs+ allocated_entry_ids = confirmed_entry_ids+ occurrences_by_series = occurrences.group_by(&:recurring_transaction_id)++ candidates = entries_for(occurrences, include_closed_window).flat_map do |entry|+ next [] if allocated_entry_ids.include?(entry.id)++ occurrences_by_series.flat_map do |series_id, series_occurrences|+ series = series_occurrences.first.recurring_transaction+ next [] if rejected.include?([ series_id, entry.id ])+ next [] unless identity_matches?(series, entry)++ series_occurrences.filter_map do |occurrence|+ next unless within_window?(occurrence, entry)++ confidence, signals = score(occurrence, series, entry)+ next if confidence < HIGH_TIER++ Candidate.new(occurrence: occurrence, entry: entry, confidence: confidence, signals: signals)+ end+ end+ end++ prune_to_nearest_per_series(candidates)+ end++ # Within one series an entry pairs only with its nearest open occurrence.+ # The cross-series ambiguity guard still applies; this stops a backlog of+ # overdue cycles from making every payment look ambiguous against itself.+ # The ambiguity guard exists for CROSS-series twins; same-series+ # assignment is date arithmetic, not a judgment call.+ def prune_to_nearest_per_series(candidates)+ candidates.group_by { |candidate| [ candidate.entry.id, candidate.occurrence.recurring_transaction_id ] }+ .values+ .map { |group| group.min_by { |candidate| (candidate.entry.date - candidate.occurrence.effective_due_on).to_i.abs } }+ end++ def open_occurrences+ family.recurring_occurrences+ .open_status+ .includes(recurring_transaction: :recurrence_rules)+ .reject { |occurrence| occurrence.recurring_transaction.transfer? }+ end++ def rejected_pairs+ RecurringMatchRejection+ .joins(:recurring_transaction)+ .where(recurring_transactions: { family_id: family.id })+ .pluck(:recurring_transaction_id, :entry_id)+ .to_set+ end++ def confirmed_entry_ids+ RecurringAllocation+ .joins(:recurring_occurrence)+ .where(recurring_occurrences: { family_id: family.id })+ .where(state: "confirmed")+ .where.not(entry_id: nil)+ .pluck(:entry_id)+ .to_set+ end++ # One query over the envelope of every open occurrence's window.+ def entries_for(occurrences, include_closed_window)+ window_min = occurrences.map { |occurrence| window_for(occurrence).begin }.min+ window_max = occurrences.map { |occurrence| window_for(occurrence).end }.max+ window_max = Date.current if !include_closed_window && window_max > Date.current++ family.entries+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id")+ .where(entryable_type: "Transaction")+ .where(excluded: false)+ .where(date: window_min..window_max)+ .where.not(transactions: { kind: Transaction::TRANSFER_KINDS })+ .where.not(id: RecurringAllocation.where.not(entry_id: nil).where(state: "confirmed").select(:entry_id))+ .includes(:entryable)+ .to_a+ end++ # The occurrence's date window, snooze-aware and clamped so adjacent+ # occurrences of one series can never both claim the same entry: each+ # side caps at just under half the cycle length. Overdue occurrences+ # additionally stay matchable to today -- a late payment is exactly the+ # case the overdue workflow exists for.+ def window_for(occurrence)+ @windows ||= {}+ @windows[occurrence.id] ||= begin+ series = occurrence.recurring_transaction+ cycle_days = (365.25 / series.schedule.occurrences_per_year).floor+ half_cycle = [ (cycle_days - 1) / 2, 1 ].max++ early = [ series.match_days_early, half_cycle ].min+ late = [ series.match_days_late, half_cycle ].min++ window_start = occurrence.effective_due_on - early+ window_end = occurrence.effective_due_on + late+ window_end = [ window_end, Date.current ].max if occurrence.derived_state == :overdue++ window_start..window_end+ end+ end++ def within_window?(occurrence, entry)+ window_for(occurrence).cover?(entry.date)+ end++ # Looser than identity_matches? on purpose, see repair_orphans!: a repost+ # keeps the merchant when it has one, and its name stays kin to the old+ # descriptor rather than equal to it.+ def repair_identity?(series, entry)+ if series.merchant_id.present? && entry.entryable.merchant_id.present?+ return entry.entryable.merchant_id == series.merchant_id+ end++ candidate = normalize_name(entry.name)+ known_names(series).any? do |known|+ candidate == known || candidate.start_with?(known) || known.start_with?(candidate)+ end+ end++ # Hard filters: right sign, right currency, right account when the+ # series is account-scoped, and the identifier at least plausibly+ # related (same merchant, or a name the series knows).+ def identity_matches?(series, entry)+ return false unless entry.currency == series.currency+ return false if series.account_id.present? && entry.account_id != series.account_id++ expense_series = series.amount.positive?+ return false if expense_series != entry.amount.positive?++ if series.merchant_id.present?+ entry.entryable.merchant_id == series.merchant_id+ else+ known_names(series).include?(normalize_name(entry.name))+ end+ end++ def known_names(series)+ @known_names ||= {}+ @known_names[series.id] ||= ([ series.name ] + Array(series.matcher_hints["name_aliases"]))+ .compact.map { |name| self.class.normalize_name(name) }.to_set+ end++ def normalize_name(name)+ self.class.normalize_name(name)+ end++ # Memoized per occurrence: resolved_expected_amount is not cached on the+ # model, and under the "last" amount strategy it runs an ordered LIMIT 1+ # plus a SUM. Scoring a list of candidates against one occurrence would+ # otherwise re-ask that question once per candidate.+ def expected_for(occurrence)+ @expected ||= {}+ @expected[occurrence.id] ||= occurrence.resolved_expected_amount+ end++ def score(occurrence, series, entry)+ signals = {}+ expected = expected_for(occurrence)++ if series.merchant_id.present?+ signals[:merchant] = 0.40+ else+ signals[:name] = 0.35+ end++ signals[:amount] = amount_score(series, expected, entry.amount.abs)+ return [ BigDecimal("0"), signals ] if signals[:amount].nil?++ signals[:date] = date_score(occurrence, entry.date)+ signals[:account] = 0.10 if entry.account_id == series.account_id || series.account_id.nil?++ [ signals.values.sum.to_d.round(4), signals ]+ end++ # Exact amount scores 0.30; within tolerance decays 0.25 -> 0.15 with+ # distance from expected; outside tolerance kills the candidate.+ def amount_score(series, expected, actual)+ return 0.30 if (actual - expected).abs < BigDecimal("0.01")++ tolerance_pct = [ series.amount_tolerance_pct, learned_tolerance(series) ].max+ band = expected.abs * (tolerance_pct / BigDecimal("100"))+ distance = (actual - expected).abs+ return nil if band.zero? || distance > band++ (0.25 - (distance / band) * 0.10).round(4)+ end++ def learned_tolerance(series)+ BigDecimal((series.matcher_hints["learned_tolerance_pct"] || 0).to_s)+ end++ # 0.20 on the due date, decaying linearly to 0.05 at the window edge.+ def date_score(occurrence, date)+ window = window_for(occurrence)+ span = [ (window.end - window.begin).to_i, 1 ].max+ distance = (date - occurrence.effective_due_on).to_i.abs++ (0.20 - ([ distance, span ].min.to_f / span) * 0.15).round(4)+ end+ end+enddiff --git a/app/models/recurring_transaction/occurrence_generator.rb b/app/models/recurring_transaction/occurrence_generator.rbnew file mode 100644index 0000000000..a05fde0f24--- /dev/null+++ b/app/models/recurring_transaction/occurrence_generator.rb@@ -0,0 +1,94 @@+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+enddiff --git a/app/models/recurring_transaction/paycheck_planner.rb b/app/models/recurring_transaction/paycheck_planner.rbnew file mode 100644index 0000000000..db707dcaed--- /dev/null+++ b/app/models/recurring_transaction/paycheck_planner.rb@@ -0,0 +1,306 @@+class RecurringTransaction+ # Slices time by the family's declared income schedule and funds every open+ # obligation from the paycheck of the window it falls due in, so each period+ # reports what is due inside it, what it holds for a later bill that outgrows+ # its own paycheck, and what is safe once both are taken out.+ #+ # Only manually declared income defines paydays; detected inflows never do.+ class PaycheckPlanner+ # `remaining_total` is the whole obligation this share is a slice of,+ # pre-converted to the family currency so no view has to convert money.+ Item = Data.define(:occurrence, :share, :remaining_total, :due_in_period)++ Period = Data.define(+ :starts_on, :ends_on, :income, :income_sources, :items,+ :due_total, :reserved_total, :obligation_total, :remaining, :leading, :final,+ :cash_on_hand+ ) do+ # The window between today and the next payday: nothing arrives in it, so+ # what it needs must come from cash already in hand.+ def bridge?+ leading && !income.positive?+ end++ # A bridge window earns no income by construction, so measuring it the+ # way every other window is measured guarantees a shortfall the instant+ # any bill falls inside it. That is not a warning, it is a restatement of+ # having a bill before payday, and it fired for everyone who did.+ #+ # What actually decides whether that window is a problem is the cash+ # already in hand, which is what this always claimed to compare and never+ # did. When the balance cannot be established, cash_on_hand is nil and+ # nothing is claimed: an unknown balance is not evidence of a shortfall.+ def short?+ if bridge?+ # An unknown balance is not evidence of a shortfall.+ cash_on_hand.present? && obligation_total > cash_on_hand+ else+ remaining.negative?+ end+ end++ def shortfall+ return BigDecimal("0") unless short?++ bridge? ? obligation_total - cash_on_hand : -remaining+ end++ # What the cash still covers once the window's bills are met. nil when+ # the balance is unknown, so copy can stay quiet rather than guess.+ def cash_after_obligations+ return nil unless bridge? && cash_on_hand.present?++ 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.+ def items_due+ items.select(&:due_in_period).sort_by { |item| item.occurrence.due_on }+ end++ def items_reserved+ items.reject(&:due_in_period).sort_by { |item| item.occurrence.due_on }+ end++ # By what the bill actually costs, not by the slice this period carries.+ def largest_obligation+ items.max_by(&:remaining_total)+ end+ end++ attr_reader :family, :user, :unconvertible_count++ def initialize(family, user:)+ @family = family+ @user = user+ @unconvertible_count = 0+ end++ # nil when no income schedule is declared (the view prompts for one).+ def plan(periods_limit: 3)+ incomes = upcoming_income_occurrences+ return nil if incomes.empty?++ boundaries = period_boundaries(incomes, periods_limit)+ periods = build_periods(boundaries, incomes)+ # A single boundary (every upcoming paycheck lands today) yields no+ # periods to spread anything across.+ return [] if periods.empty?++ apportion_bills(periods)++ periods.map do |period|+ due_total = period[:items].sum { |item| item.due_in_period ? item.share : 0 }+ reserved_total = period[:items].sum { |item| item.due_in_period ? 0 : item.share }+ obligation_total = due_total + reserved_total++ Period.new(+ starts_on: period[:starts_on],+ ends_on: period[:ends_on],+ income: period[:income],+ income_sources: period[:income_sources],+ items: period[:items].sort_by { |item| -item.share },+ due_total: due_total,+ reserved_total: reserved_total,+ obligation_total: obligation_total,+ remaining: period[:income] - obligation_total,+ leading: period[:leading],+ final: period[:final],+ cash_on_hand: period[:leading] ? cash_on_hand : nil+ )+ end+ end++ # Every declared income series' next arrival, keyed by series id. Read from+ # occurrences, never from `next_expected_date`: a paycheck that did not turn+ # up is not overdue, it is simply not the next one.+ def next_income_by_series+ upcoming_income_occurrences.each_with_object({}) do |occurrence, index|+ index[occurrence.recurring_transaction_id] ||= occurrence+ end+ end++ private+ # Declared income only. Sign alone proves nothing: a recurring one-cent+ # balance transfer is income by sign and a payday by nothing.+ def upcoming_income_occurrences+ @upcoming_income_occurrences ||=+ family.recurring_occurrences+ .open_status+ .joins(:recurring_transaction)+ .where(recurring_transactions: { status: :active, bill_type: :income, manual: true })+ .merge(RecurringTransaction.accessible_by(user))+ .where("recurring_occurrences.due_on >= ?", Date.current)+ .includes(:recurring_transaction)+ .order(:due_on)+ .to_a+ end++ # Today up to the first paycheck is its own period, then one per paycheck.+ def period_boundaries(incomes, periods_limit)+ dates = incomes.map(&:due_on).uniq.first(periods_limit + 1)+ boundaries = ([ Date.current ] + dates).uniq++ boundaries.first(periods_limit + 2)+ end++ def build_periods(boundaries, incomes)+ boundaries.each_cons(2).map.with_index do |(starts_on, next_start), index|+ arrivals = incomes.select { |occurrence| occurrence.due_on == starts_on }++ {+ starts_on: starts_on,+ ends_on: next_start - 1,+ income: arrivals.sum { |occurrence| to_family_currency(occurrence.resolved_expected_amount_money) },+ income_sources: arrivals.map { |occurrence| occurrence.recurring_transaction.display_name }.uniq,+ items: [],+ leading: index.zero?,+ final: false+ }+ end.tap { |periods| periods.last[:final] = true if periods.any? }+ end++ # Each obligation is funded by the paycheck of the window it falls due+ # in. Only what that paycheck cannot cover cascades backward into earlier+ # windows as reserves, nearest paycheck first, so a reserve always means+ # a bill outgrew one paycheck and never bookkeeping noise. Overflow no+ # earlier paycheck can absorb piles onto the earliest one, surfacing the+ # shortfall today instead of the week the bill lands.+ #+ # A reserve has to come out of a paycheck, so only periods that receive+ # income can carry one. The leading window is the gap before the next+ # payday and has no income by definition: it carries only what genuinely+ # falls due inside it, paid from cash already in hand.+ def apportion_bills(periods)+ available = periods.map { |period| period[:income] }++ # 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 ] }++ 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+ home = periods.index { |period| effective_due.between?(period[:starts_on], period[:ends_on]) }+ next if home.nil?++ funded = [ remaining, [ available[home], 0 ].max ].min+ uncovered = remaining - funded++ # Earlier paychecks, nearest first. The earliest takes whatever the+ # others could not and goes short, so the gap shows now rather than+ # the week the bill arrives.+ sources = (0...home).select { |index| periods[index][:income].positive? }.reverse++ sources.each do |index|+ break unless uncovered.positive?++ take = index == sources.last ? uncovered : [ uncovered, [ available[index], 0 ].max ].min+ next unless take.positive?++ available[index] -= take+ uncovered -= take+ periods[index][:items] << Item.new(+ occurrence: occurrence,+ share: take,+ remaining_total: remaining,+ due_in_period: false+ )+ end++ # With no earlier paycheck to lean on, the bill's own window carries+ # all of it, shortfall included.+ funded += uncovered if uncovered.positive?++ available[home] -= funded+ periods[home][:items] << Item.new(+ occurrence: occurrence,+ share: funded,+ remaining_total: remaining,+ due_in_period: true+ )+ end+ end++ def open_payable_occurrences(through)+ # Family-scoped: an unbounded subquery here scans every account in the+ # installation.+ debt_accounts = Account.where(family_id: family.id, accountable_type: %w[CreditCard Loan]).select(:id)++ family.recurring_occurrences+ .open_status+ .joins(:recurring_transaction)+ .where(recurring_transactions: { status: :active })+ .where("recurring_transactions.amount > 0")+ .merge(+ RecurringTransaction.where(destination_account_id: nil)+ .or(RecurringTransaction.where(destination_account_id: debt_accounts))+ )+ .merge(RecurringTransaction.accessible_by(user))+ .where("recurring_occurrences.due_on <= ?", through)+ .includes(recurring_transaction: :merchant)+ .to_a+ .tap { |occurrences| preload_confirmed_sums(occurrences) }+ end++ # Cash a bill can actually be paid from before the next paycheck: the+ # family's own deposit accounts, minus the tax-advantaged ones nobody+ # spends rent out of. Credit cards share the `:cash` balance type but are+ # a liability, so they are not money on hand.+ #+ # nil, never zero, when there is nothing to read. Zero would assert the+ # user is broke and raise a shortfall on that basis; nil says the balance+ # is unknown and the window goes unjudged.+ def cash_on_hand+ return @cash_on_hand if defined?(@cash_on_hand)++ accounts = family.accounts.visible+ .where(accountable_type: "Depository")+ .merge(Account.accessible_by(user))++ excluded = family.tax_advantaged_account_ids+ accounts = accounts.where.not(id: excluded) if excluded.present?++ @cash_on_hand =+ if accounts.exists?+ # One unconvertible account must not shrink the balance silently: a+ # partial sum reads as "short" when the missing account might cover+ # everything. Unknown stays unknown.+ balances = accounts.map do |account|+ account.balance_money.exchange_to(family.currency).amount+ rescue Money::ConversionError+ @unconvertible_count += 1+ nil+ end++ balances.sum unless balances.include?(nil)+ end+ end++ # An unconvertible obligation is counted and reported, never folded in as+ # zero, which would inflate what the plan says is safe to spend.+ # remaining_amount aggregates confirmed allocations per occurrence, one+ # query each. Same grouped-sum-into-the-cache pattern the bills tools and+ # BudgetCategory#bills_reservation already use.+ def preload_confirmed_sums(occurrences)+ sums = RecurringAllocation.confirmed+ .where(recurring_occurrence_id: occurrences.map(&:id))+ .group(:recurring_occurrence_id)+ .sum(:allocated_amount)+ occurrences.each { |occurrence| occurrence.cached_confirmed_allocated = sums.fetch(occurrence.id, 0) }+ end++ def to_family_currency(money)+ money.exchange_to(family.currency).amount+ rescue Money::ConversionError+ @unconvertible_count += 1+ BigDecimal("0")+ end+ end+enddiff --git a/app/models/recurring_transaction/pipeline.rb b/app/models/recurring_transaction/pipeline.rbnew file mode 100644index 0000000000..c3db21ca5c--- /dev/null+++ b/app/models/recurring_transaction/pipeline.rb@@ -0,0 +1,77 @@+class RecurringTransaction+ # The full detection pipeline -- identify patterns, materialize occurrence+ # windows, repair provider-replaced entries, match payments, detect price+ # changes -- in one place for its three callers: the post-sync job, the+ # Settings "Identify Patterns" button, and the Bills page's detection action.+ #+ # `run!` returns the identified pattern count. `backfill: true` additionally+ # reconstructs recent history after the five stages; user-triggered detection+ # asks for it, background syncs never do. `run_with_lock!` returns the count,+ # or nil when another run already holds the family lock.+ class Pipeline+ FIRST_RUN_BACKFILL_MONTHS = 6++ attr_reader :family++ def initialize(family)+ @family = family+ end++ def run!(backfill: false)+ patterns_count = Identifier.new(family).identify_recurring_patterns++ family.recurring_transactions.active.find_each do |series|+ OccurrenceGenerator.new(series).generate!+ end++ matcher = Matcher.new(family)+ matcher.repair_orphans!+ matcher.run!+ PriceChangeDetector.new(family).detect!++ # Unconditional when asked: the backfiller is idempotent, so re-running+ # it reconstructs nothing twice.+ HistoryBackfiller.new(family, months: FIRST_RUN_BACKFILL_MONTHS).run! if backfill++ patterns_count+ end++ # User-triggered runs refuse to stack on top of an in-flight pipeline+ # (debounced job or nightly sweep) instead of running concurrently.+ def run_with_lock!(backfill: false)+ result = nil+ acquired = self.class.with_family_lock(family.id) { result = run!(backfill: backfill) }+ acquired ? result : nil+ end++ # One advisory lock per family, shared by every pipeline caller. Returns+ # true when the lock was acquired and the block ran.+ def self.with_family_lock(family_id)+ lock_key = advisory_lock_key(family_id)+ # One leased connection for both halves: the unlock must run on the same+ # PostgreSQL session that took the lock, and bare .connection is+ # soft-deprecated in Rails 8.1.+ connection = ActiveRecord::Base.lease_connection+ acquired = connection.select_value(+ ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_try_advisory_lock(?)", lock_key ])+ )++ return false unless acquired++ begin+ yield+ ensure+ connection.execute(+ ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_advisory_unlock(?)", lock_key ])+ )+ end+ true+ end++ # The key string predates this class; keeping it byte-identical means an+ # upgraded deploy still serializes against jobs queued by the old build.+ def self.advisory_lock_key(family_id)+ Digest::MD5.hexdigest("recurring_transaction_identify:#{family_id}").to_i(16) % (2**31)+ end+ end+enddiff --git a/app/models/recurring_transaction/price_change_detector.rb b/app/models/recurring_transaction/price_change_detector.rbnew file mode 100644index 0000000000..b2b5fa8cb7--- /dev/null+++ b/app/models/recurring_transaction/price_change_detector.rb@@ -0,0 +1,75 @@+class RecurringTransaction+ # Notices when a bill's real charges settle on a new price and keeps the+ # series honest about it. Two consecutive paid occurrences, each settled by+ # a single payment, agreeing on an amount different from the series' --+ # that is a price change, not noise. One odd charge is never enough.+ #+ # Auto-detected series get their amount updated (detection created them,+ # detection maintains them); manually declared series only get the price+ # change RECORDED -- the user stated that amount, so the user changes it,+ # with the recorded change surfacing the suggestion.+ class PriceChangeDetector+ EPSILON = BigDecimal("0.01")++ attr_reader :family++ def initialize(family)+ @family = family+ end++ def detect!+ changes = 0++ family.recurring_transactions.active.where("amount > 0").find_each do |series|+ changes += 1 if detect_for(series)+ end++ changes+ end++ private+ def detect_for(series)+ recent = series.recurring_occurrences+ .paid+ .order(due_on: :desc)+ .limit(2)+ .includes(:allocations)+ .to_a+ return false unless recent.size == 2++ settlements = recent.map do |occurrence|+ confirmed = occurrence.allocations.select(&:allocation_confirmed?)+ # Only single-payment settlements speak to the PRICE; a pile of+ # partials says nothing about what the biller charges.+ confirmed.size == 1 ? confirmed.first : nil+ end+ return false if settlements.any?(&:nil?)++ totals = settlements.map(&:allocated_amount)+ return false unless (totals.first - totals.last).abs <= EPSILON++ new_amount = totals.first+ return false if (new_amount - series.amount.abs).abs <= EPSILON++ effective_on = recent.first.due_on+ return false if series.recurring_price_changes.exists?(effective_on: effective_on)+ return false if series.recurring_price_changes.order(:effective_on).last&.new_amount == new_amount++ RecurringPriceChange.create!(+ recurring_transaction: series,+ effective_on: effective_on,+ previous_amount: series.amount.abs,+ new_amount: new_amount,+ currency: series.currency,+ source: "detected",+ entry: settlements.first.entry+ )++ series.update!(amount: new_amount) unless series.manual?++ true+ rescue ActiveRecord::RecordNotUnique+ false+ end+ end+enddiff --git a/app/models/recurring_transaction/schedule.rb b/app/models/recurring_transaction/schedule.rbnew file mode 100644index 0000000000..9299bc8768--- /dev/null+++ b/app/models/recurring_transaction/schedule.rb@@ -0,0 +1,415 @@+class RecurringTransaction+ # All date math for a recurring transaction, driven by its recurrence_rules.+ # A series with no rules gets an implicit "monthly on expected_day_of_month".+ #+ # Two families of methods coexist:+ #+ # * first_occurrence_after / occurrences_between / cycle_for -- the+ # rules-based engine. New code uses these.+ # * next_occurrence_after / next_occurrence_from_today -- shims that keep+ # next_expected_date persistence byte-identical for existing series, and+ # fall through to the engine for rule shapes they cannot express.+ class Schedule+ # How far an entry's day-of-month may drift from the expected day and+ # still count as the same occurrence.+ DAY_MATCH_TOLERANCE = 2++ # Weekend-adjusted occurrences move at most 2 days; raw generation pads+ # its range by this much so adjusted dates cannot escape a query window.+ WEEKEND_MARGIN = 3++ # first_occurrence_after gives up after this many days: weekend-skip can+ # drop consecutive occurrences, so the search loops, but boundedly.+ SEARCH_CAP_DAYS = 366 * 10++ Rule = Data.define(:frequency, :interval, :day_of_month, :weekday, :weekday_ordinal, :month_of_year)++ attr_reader :rules, :anchor_date, :weekend_adjust, :end_mode, :end_on, :end_after_count,+ :expected_day_of_month++ def self.for(recurring_transaction)+ new(+ expected_day_of_month: recurring_transaction.expected_day_of_month,+ rules: recurring_transaction.recurrence_rules.map { |rule|+ Rule.new(+ frequency: rule.frequency,+ interval: rule.interval,+ day_of_month: rule.day_of_month,+ weekday: rule.weekday,+ weekday_ordinal: rule.weekday_ordinal,+ month_of_year: rule.month_of_year+ )+ },+ anchor_date: recurring_transaction.anchor_date || recurring_transaction.last_occurrence_date,+ weekend_adjust: recurring_transaction.weekend_adjust,+ end_mode: recurring_transaction.end_mode,+ end_on: recurring_transaction.end_on,+ end_after_count: recurring_transaction.end_after_count+ )+ end++ def initialize(expected_day_of_month:, rules: [], anchor_date: nil, weekend_adjust: "none",+ end_mode: "never", end_on: nil, end_after_count: nil)+ @expected_day_of_month = expected_day_of_month+ @rules = rules.presence || [ implicit_monthly_rule ]+ @anchor_date = anchor_date+ @weekend_adjust = weekend_adjust+ @end_mode = end_mode+ @end_on = end_on+ @end_after_count = end_after_count++ if @rules.any? { |rule| rule.interval > 1 } && @anchor_date.nil?+ raise ArgumentError, "an anchor_date is required when a rule repeats every 2 or more periods"+ end+ if @end_mode == "after_count" && @anchor_date.nil?+ raise ArgumentError, "an anchor_date is required to count occurrences from"+ end+ end++ # Distance between two days on the 31-day calendar circle, so the 30th+ # and the 1st are two days apart, not twenty-nine.+ def self.circular_day_distance(day1, day2)+ linear = (day1 - day2).abs+ [ linear, 31 - linear ].min+ end++ # SQL fragment selecting entries whose day-of-month lies within+ # DAY_MATCH_TOLERANCE of :expected_day on the circular calendar, with the+ # expected day clamped into short months (a day-31 bill matches Feb 28).+ # Callers bind :expected_day and :tolerance.+ def self.day_window_sql+ clamped = "LEAST(:expected_day, EXTRACT(DAY FROM (DATE_TRUNC('month', entries.date) + INTERVAL '1 month' - INTERVAL '1 day')))"+ distance = "ABS(EXTRACT(DAY FROM entries.date) - #{clamped})"+ "LEAST(#{distance}, 31 - #{distance}) <= :tolerance"+ end++ # Ruby-side twin of day_window_sql for code that already holds the entry.+ # Matches against each rule's own generated occurrences, so an every-N+ # cadence rejects dates that sit on the right weekday or day-of-month but+ # in the wrong cycle. A weekly cadence repeats on an exact weekday (no+ # drift tolerance); the day-of-month window only fits the others. End+ # conditions and weekend adjustment apply exactly as in materialization:+ # an ended series stops claiming entries, and an adjusted occurrence also+ # matches the day it is actually due.+ def matches_day?(date)+ rules.any? { |rule| rule_matches_day?(rule, date) }+ end++ # --- The rules-based engine ---++ # A single generated occurrence: the raw schedule date (the occurrence's+ # permanent identity) and the weekend-adjusted date it is actually due.+ Pair = Data.define(:original_due_on, :due_on)++ # Every occurrence whose due date falls in the range, as (original, due)+ # pairs. Occurrence rows key on the original, so identity survives weekend+ # adjustment and rule edits that do not move the raw date.+ def occurrence_pairs_between(start_date, end_date)+ return [] if start_date > end_date++ if end_mode == "after_count"+ # Both bounds: lifetime_pairs computes through the anchor even when+ # the anchor sits past end_date, so a future-anchored plan would+ # otherwise leak its first occurrence into a window that ends today.+ lifetime_pairs(through: end_date).select { |pair| pair.due_on >= start_date && pair.due_on <= end_date }+ else+ adjusted_pairs(start_date, end_date)+ end+ end++ # Every occurrence with start_date <= date <= end_date, weekend-adjusted,+ # end-mode-truncated, sorted, deduplicated.+ def occurrences_between(start_date, end_date)+ occurrence_pairs_between(start_date, end_date).map(&:due_on).uniq.sort+ end++ # First occurrence strictly after `date`, or nil once the series has ended.+ # Contrast the shim next_occurrence_after below.+ def first_occurrence_after(date)+ window = longest_period_days+ cursor = date + 1++ while cursor <= date + SEARCH_CAP_DAYS+ found = occurrences_between(cursor, cursor + window).first+ return found if found+ return nil if ended_before?(cursor + window)++ cursor += window + 1+ end++ nil+ end++ # The period containing `date`: from the last occurrence on-or-before it+ # (inclusive) up to the next one (exclusive). A monthly bill's cycle is+ # its billing month.+ def cycle_for(date)+ window = longest_period_days+ lookback = occurrences_between(date - window * 2, date)+ cycle_start = lookback.last || first_occurrence_after(date - window * 2 - 1)+ return nil if cycle_start.nil?++ cycle_end = first_occurrence_after(cycle_start)+ return nil if cycle_end.nil?++ cycle_start...cycle_end+ end++ # Average occurrences per year across all rules; the model turns this+ # into a monthly-equivalent amount for cadence-normalized totals.+ def occurrences_per_year+ rules.sum do |rule|+ case rule.frequency+ when "weekly" then 365.25 / (7.0 * rule.interval)+ when "monthly" then 12.0 / rule.interval+ when "yearly" then 1.0 / rule.interval+ end+ end+ end++ # --- Legacy shims (see class comment) ---++ def next_occurrence_after(date)+ return first_occurrence_after(date) unless legacy_monthly?++ occurrence_in_month(date.next_month)+ end++ def next_occurrence_from_today+ return first_occurrence_after(Date.current) unless legacy_monthly?++ today = Date.current++ begin+ this_month = Date.new(today.year, today.month, expected_day_of_month)+ return this_month if this_month > today+ rescue ArgumentError+ # Preserved quirk: no clamping here -- a day-31 bill skips February+ # entirely and lands on March 31.+ end++ occurrence_in_month(today.next_month)+ end++ private+ def rule_matches_day?(rule, date)+ if rule.frequency == "weekly"+ # A weekly rule without a weekday inherits the anchor's; with+ # neither there is nothing to reject on, so any day matches.+ weekday = rule.weekday || anchor_date&.wday+ return true if weekday.nil?++ rule_occurrence_near?(rule.with(weekday: weekday), date, 0)+ else+ rule_occurrence_near?(rule, date, DAY_MATCH_TOLERANCE)+ end+ end++ # True when one of the rule's occurrences is observable within+ # `tolerance` days of `date`: on its raw scheduled day (the occurrence's+ # identity, where a payment can still post) or on its weekend-adjusted+ # due day. Occurrences the end conditions remove match nothing, and a+ # skipped-weekend occurrence does not exist at all.+ def rule_occurrence_near?(rule, date, tolerance)+ window = tolerance + WEEKEND_MARGIN+ raw_occurrences(rule, date - window, date + window).any? do |original|+ due = adjust_for_weekend(original)+ next false if due.nil? || past_end_date?(due) || beyond_occurrence_count?(original)++ (original - date).abs <= tolerance || (due - date).abs <= tolerance+ end+ end++ # Under an after_count end, an occurrence only exists while it is one of+ # the series' first end_after_count occurrences, counted from the anchor.+ def beyond_occurrence_count?(original)+ return false unless end_mode == "after_count"++ lifetime_pairs(through: original + WEEKEND_MARGIN)+ .none? { |pair| pair.original_due_on == original }+ end++ def implicit_monthly_rule+ raise ArgumentError, "a schedule needs rules or an expected_day_of_month" if expected_day_of_month.nil?++ Rule.new(frequency: "monthly", interval: 1, day_of_month: expected_day_of_month,+ weekday: nil, weekday_ordinal: nil, month_of_year: nil)+ end++ # True for the one shape the pre-rules code could express: a single+ # monthly day-of-month rule with no interval, adjustment, or end. Only+ # these series get the preserved quirks.+ def legacy_monthly?+ # The shim builds Date.new from this value, and a nil raises TypeError,+ # which the ArgumentError rescue does not cover.+ expected_day_of_month.present? &&+ rules.size == 1 &&+ rules.first.frequency == "monthly" &&+ rules.first.day_of_month.present? &&+ rules.first.day_of_month != RecurrenceRule::LAST &&+ rules.first.interval == 1 &&+ weekend_adjust == "none" &&+ end_mode == "never"+ end++ def adjusted_pairs(start_date, end_date)+ raw = rules.flat_map { |rule| raw_occurrences(rule, start_date - WEEKEND_MARGIN, end_date + WEEKEND_MARGIN) }++ raw.uniq.sort.filter_map { |original|+ due = adjust_for_weekend(original)+ next if due.nil?+ next unless due >= start_date && due <= end_date && !past_end_date?(due)++ Pair.new(original_due_on: original, due_on: due)+ }+ end++ # The series' first end_after_count occurrences, counted from the+ # anchor, up to `through`. Membership keys on the raw scheduled date:+ # the lookup starts before the anchor so an anchor occurrence moved+ # earlier by weekend_adjust "before" still counts as the first one.+ def lifetime_pairs(through:)+ adjusted_pairs(anchor_date - WEEKEND_MARGIN, [ through, anchor_date ].max)+ .select { |pair| pair.original_due_on >= anchor_date }+ .first(end_after_count)+ end++ def lifetime_occurrences(through:)+ lifetime_pairs(through: through).map(&:due_on)+ end++ def past_end_date?(date)+ end_mode == "on_date" && end_on.present? && date > end_on+ end++ def ended_before?(date)+ case end_mode+ when "on_date" then end_on.present? && end_on < date+ when "after_count" then lifetime_occurrences(through: date).size >= end_after_count+ else false+ end+ end++ def adjust_for_weekend(date)+ return date unless date.saturday? || date.sunday?++ case weekend_adjust+ when "skip" then nil+ when "before" then date.saturday? ? date - 1 : date - 2+ when "after" then date.saturday? ? date + 2 : date + 1+ else date+ end+ end++ def raw_occurrences(rule, start_date, end_date)+ case rule.frequency+ when "weekly" then weekly_occurrences(rule, start_date, end_date)+ when "monthly" then monthly_occurrences(rule, start_date, end_date)+ when "yearly" then yearly_occurrences(rule, start_date, end_date)+ end+ end++ # The anchor fixes WHICH week/month/year an every-N cadence fires in;+ # occurrences extend backward as well as forward so history can be+ # reconstructed (catch-up/backfill).+ def weekly_occurrences(rule, start_date, end_date)+ # Same fallback as rule_matches_day?: a weekly rule without a weekday+ # inherits the anchor's. With neither there is no day to generate on.+ weekday = rule.weekday || anchor_date&.wday+ raise ArgumentError, "a weekly rule needs a weekday or an anchor_date" if weekday.nil?++ step = 7 * rule.interval+ reference = anchor_date || start_date+ base = reference + ((weekday - reference.wday) % 7)++ first_step = ((start_date - base).to_i.to_f / step).ceil+ occurrences = []+ cursor = base + first_step * step+ while cursor <= end_date+ occurrences << cursor+ cursor += step+ end+ occurrences+ end++ def monthly_occurrences(rule, start_date, end_date)+ reference_month = month_index(anchor_date || start_date)++ occurrences = []+ month = Date.new(start_date.year, start_date.month, 1)+ while month <= end_date+ if (month_index(month) - reference_month) % rule.interval == 0+ date = date_in_month(rule, month)+ occurrences << date if date && date >= start_date && date <= end_date+ end+ month = month.next_month+ end+ occurrences+ end++ def yearly_occurrences(rule, start_date, end_date)+ reference_year = (anchor_date || start_date).year++ occurrences = []+ (start_date.year..end_date.year).each do |year|+ next unless (year - reference_year) % rule.interval == 0++ date = date_in_month(rule, Date.new(year, rule.month_of_year, 1))+ occurrences << date if date && date >= start_date && date <= end_date+ end+ occurrences+ end++ def month_index(date)+ date.year * 12 + date.month+ end++ # The rule's day within the given month: a day-of-month (clamped into+ # short months, -1 meaning the last day) or an nth weekday (nil when+ # the month has no 5th such weekday, skipping that month).+ def date_in_month(rule, month_start)+ if rule.day_of_month.present?+ return month_start.end_of_month if rule.day_of_month == RecurrenceRule::LAST++ begin+ Date.new(month_start.year, month_start.month, rule.day_of_month)+ rescue ArgumentError+ month_start.end_of_month+ end+ else+ nth_weekday_in_month(month_start, rule.weekday, rule.weekday_ordinal)+ end+ end++ def nth_weekday_in_month(month_start, weekday, ordinal)+ if ordinal == RecurrenceRule::LAST+ month_end = month_start.end_of_month+ month_end - ((month_end.wday - weekday) % 7)+ else+ first = month_start + ((weekday - month_start.wday) % 7)+ candidate = first + 7 * (ordinal - 1)+ candidate.month == month_start.month ? candidate : nil+ end+ end++ # The longest gap between two consecutive occurrences of any rule, in+ # days, padded. Used to size search windows.+ def longest_period_days+ rules.map { |rule|+ case rule.frequency+ when "weekly" then 7 * rule.interval+ when "monthly" then 31 * rule.interval+ when "yearly" then 366 * rule.interval+ end+ }.max + 40+ end++ # The expected day within the given month, clamped to the month's end.+ # Serves the legacy shims only.+ def occurrence_in_month(date)+ Date.new(date.year, date.month, expected_day_of_month)+ rescue ArgumentError+ date.end_of_month+ end+ end+enddiff --git a/app/views/api/v1/recurring_transactions/_recurring_transaction.json.jbuilder b/app/views/api/v1/recurring_transactions/_recurring_transaction.json.jbuilderindex c103ed53b0..a64b15d92a 100644--- a/app/views/api/v1/recurring_transactions/_recurring_transaction.json.jbuilder+++ b/app/views/api/v1/recurring_transactions/_recurring_transaction.json.jbuilder@@ -14,12 +14,33 @@ json.status recurring_transaction.statusjson.occurrence_count recurring_transaction.occurrence_countjson.name recurring_transaction.namejson.manual recurring_transaction.manual+json.payment_url recurring_transaction.payment_url+json.autopay recurring_transaction.autopay+json.notes recurring_transaction.notesjson.expected_amount_min recurring_transaction.expected_amount_min_money&.formatjson.expected_amount_min_cents money_to_minor_units.call(recurring_transaction.expected_amount_min_money)json.expected_amount_max recurring_transaction.expected_amount_max_money&.formatjson.expected_amount_max_cents money_to_minor_units.call(recurring_transaction.expected_amount_max_money)json.expected_amount_avg recurring_transaction.expected_amount_avg_money&.formatjson.expected_amount_avg_cents money_to_minor_units.call(recurring_transaction.expected_amount_avg_money)+json.bill_type recurring_transaction.bill_type+json.category_id recurring_transaction.category_id+json.anchor_date recurring_transaction.anchor_date+json.weekend_adjust recurring_transaction.weekend_adjust+json.end_mode recurring_transaction.end_mode+json.end_on recurring_transaction.end_on+json.end_after_count recurring_transaction.end_after_count+json.renews_on recurring_transaction.renews_on+json.trial_ends_on recurring_transaction.trial_ends_on+json.cancelled_on recurring_transaction.cancelled_on+json.recurrence_rules recurring_transaction.recurrence_rules do |rule|+ json.frequency rule.frequency+ json.interval rule.interval+ json.day_of_month rule.day_of_month+ json.weekday rule.weekday+ json.weekday_ordinal rule.weekday_ordinal+ json.month_of_year rule.month_of_year+endjson.created_at recurring_transaction.created_at.iso8601json.updated_at recurring_transaction.updated_at.iso8601diff --git a/config/brakeman.ignore b/config/brakeman.ignoreindex 463351253a..c9563c300f 100644--- a/config/brakeman.ignore+++ b/config/brakeman.ignore@@ -195,7 +195,27 @@22],"note": ""+ },+ {+ "warning_type": "Mass Assignment",+ "warning_code": 105,+ "fingerprint": "bfdd7e2efadaa4d5cb9740a250aab482c1e73bd0f46fd291af544da1c142104e",+ "check_name": "PermitAttributes",+ "message": "Potentially dangerous key allowed for mass assignment",+ "file": "app/controllers/recurring_transactions_controller.rb",+ "line": 202,+ "link": "https://brakemanscanner.org/docs/warning_types/mass_assignment/",+ "code": "params.require(:recurring_transaction).permit(:name, :amount, :account_id, :first_due_on, :frequency_preset, :payment_url, :autopay, :notes, :is_income)",+ "render_path": null,+ "location": {+ "type": "controller",+ "controller": "RecurringTransactionsController",+ "method": "new_recurring_transaction_params"+ },+ "user_input": ":account_id",+ "confidence": "High",+ "note": "account_id is never mass-assigned: build_declared_bill resolves it through Current.user.accessible_accounts.find_by, so a foreign id degrades to no account rather than an association write."}],"brakeman_version": "7.1.0"-}+}\ No newline at end of filediff --git a/config/initializers/active_record_encryption_compat.rb b/config/initializers/active_record_encryption_compat.rbnew file mode 100644index 0000000000..aebb0d6ce5--- /dev/null+++ b/config/initializers/active_record_encryption_compat.rb@@ -0,0 +1,13 @@+# frozen_string_literal: true++# Operators enabling ActiveRecord encryption on an existing self-hosted+# database can set ACTIVE_RECORD_ENCRYPTION_SUPPORT_UNENCRYPTED_DATA=true+# so rows written before encryption was configured stay readable while+# they are backfilled (re-save records, or call #encrypt on each).+require Rails.root.join("lib/active_record_encryption_config").to_s++if ActiveRecordEncryptionConfig.complete_env? &&+ ActiveModel::Type::Boolean.new.cast(ENV.fetch("ACTIVE_RECORD_ENCRYPTION_SUPPORT_UNENCRYPTED_DATA", false))+ Rails.application.config.active_record.encryption.support_unencrypted_data = true+ Rails.application.config.active_record.encryption.extend_queries = true+enddiff --git a/config/locales/models/recurrence_rule/en.yml b/config/locales/models/recurrence_rule/en.ymlnew file mode 100644index 0000000000..45cca1ead7--- /dev/null+++ b/config/locales/models/recurrence_rule/en.yml@@ -0,0 +1,27 @@+---+en:+ activerecord:+ attributes:+ recurrence_rule:+ frequency: "Frequency"+ interval: "Interval"+ day_of_month: "Day of month"+ weekday: "Weekday"+ weekday_ordinal: "Week of month"+ month_of_year: "Month"+ errors:+ models:+ recurrence_rule:+ day_spec_required: "Choose exactly one of a day of the month or a weekday"+ attributes:+ weekday:+ required_for_weekly: "is required for a weekly rule"+ weekday_ordinal:+ not_allowed_for_weekly: "does not apply to a weekly rule"+ required_with_weekday: "is required when a weekday is set"+ not_allowed_without_weekday: "only applies when a weekday is set"+ day_of_month:+ not_allowed_for_weekly: "does not apply to a weekly rule"+ month_of_year:+ required_for_yearly: "is required for a yearly rule"+ not_allowed: "only applies to a yearly rule"diff --git a/config/locales/models/recurring_allocation/en.yml b/config/locales/models/recurring_allocation/en.ymlnew file mode 100644index 0000000000..f3c08bc71c--- /dev/null+++ b/config/locales/models/recurring_allocation/en.yml@@ -0,0 +1,9 @@+---+en:+ activerecord:+ errors:+ models:+ recurring_allocation:+ attributes:+ currency:+ must_match_occurrence: must match the occurrence's currencydiff --git a/config/locales/models/recurring_transaction/en.yml b/config/locales/models/recurring_transaction/en.ymlindex 6d30296283..3b686f3207 100644--- a/config/locales/models/recurring_transaction/en.yml+++ b/config/locales/models/recurring_transaction/en.yml@@ -1,7 +1,31 @@---en:+ recurring_transactions:+ allocator:+ missing_rate: "no exchange rate from %{from} to %{to}; enter an amount explicitly"+ unmeasurable: "this transaction carries an allocation that cannot be converted to %{currency}, so what is left of it cannot be measured. Add an exchange rate for %{date} or remove the existing payment first"+ over_allocated: "allocating %{amount} exceeds the transaction's remaining %{capacity} %{currency}"activerecord:+ attributes:+ recurring_transaction:+ payment_url: "Payment link"errors:models:recurring_transaction:merchant_or_name_required: "Either merchant or name must be present"+ attributes:+ payment_url:+ invalid_scheme: "must be a valid http:// or https:// address"+ anchor_date:+ required_for_intervals: "is required when a rule repeats every 2 or more periods"+ bill_type:+ transfer_shape_mismatch: "can only be transfer when a destination account is set"+ expected_amount_min:+ greater_than_max: "cannot be greater than the expected maximum amount"+ account:+ required_for_transfer: "must be present on a recurring transfer"+ wrong_family: "must belong to this family"+ destination_account:+ same_as_source: "cannot be the same as the source account"+ family_mismatch: "must belong to the same family as the source account"+ wrong_family: "must belong to this family"diff --git a/config/locales/views/recurring_transactions/en.yml b/config/locales/views/recurring_transactions/en.ymlindex 5d57c93061..88f43ce28c 100644--- a/config/locales/views/recurring_transactions/en.yml+++ b/config/locales/views/recurring_transactions/en.yml@@ -1,6 +1,25 @@---en:recurring_transactions:+ frequency_presets:+ monthly: Monthly+ weekly: Weekly+ biweekly: Every 2 weeks+ semimonthly: Twice a month+ quarterly: Quarterly+ semiannual: Every 6 months+ annual: Yearly+ custom: Custom schedule+ frequency:+ monthly: "Monthly on the %{day}"+ weekly: "Weekly on %{weekday}"+ biweekly: "Every 2 weeks on %{weekday}"+ semimonthly: "Twice a month, the %{first} and %{second}"+ quarterly: "Quarterly on the %{day}"+ semiannual: "Every 6 months on the %{day}"+ annual: "Yearly on %{month} %{day}"+ custom: Custom schedule+ last_day: last daytitle: Recurring Transactionsupcoming: Upcoming Recurring Transactionsprojected: Projecteddiff --git a/config/schedule.yml b/config/schedule.ymlindex 11b6174590..1683540a3d 100644--- a/config/schedule.yml+++ b/config/schedule.yml@@ -55,6 +55,12 @@ refresh_demo_family:queue: "scheduled"description: "Refreshes demo family data and emails super admins with daily usage summary"+generate_recurring_occurrences:+ cron: "30 5 * * *" # daily at 5:30 AM UTC, before insights so generators see fresh occurrences+ class: "GenerateRecurringOccurrencesJob"+ queue: "scheduled"+ description: "Materializes the rolling window of recurring-transaction occurrences for every family"+generate_insights:cron: "0 6 * * *" # daily at 6:00 AM UTC, after the nightly cleanup jobsclass: "GenerateInsightsJob"diff --git a/db/migrate/20260819165021_create_bills_subsystem.rb b/db/migrate/20260819165021_create_bills_subsystem.rbnew file mode 100644index 0000000000..556a59c488--- /dev/null+++ b/db/migrate/20260819165021_create_bills_subsystem.rb@@ -0,0 +1,461 @@+# The bills subsystem's whole schema in one migration, squashed from the+# feature branch's incremental steps. DDL and the data backfills the+# incremental path carried run in their original order, so an instance+# upgrading with existing recurring_transactions rows lands on exactly the+# data the step-by-step path produced.+class CreateBillsSubsystem < ActiveRecord::Migration[7.2]+ def up+ # -- Series basics: payment link, autopay flag, freeform notes ----------+ add_column :recurring_transactions, :payment_url, :string+ add_column :recurring_transactions, :autopay, :boolean, default: false, null: false+ add_column :recurring_transactions, :notes, :text++ # -- Recurrence rules: explicit schedule definitions per series ---------+ create_table :recurrence_rules, id: :uuid do |t|+ t.references :recurring_transaction, type: :uuid, null: false,+ foreign_key: { on_delete: :cascade }, index: false+ t.string :frequency, null: false+ t.integer :interval, null: false, default: 1+ t.integer :day_of_month+ t.integer :weekday+ t.integer :weekday_ordinal+ t.integer :month_of_year+ t.integer :position, null: false, default: 0++ t.timestamps+ end++ add_index :recurrence_rules, [ :recurring_transaction_id, :position ], unique: true++ add_check_constraint :recurrence_rules, "interval > 0", name: "chk_recurrence_rules_interval_positive"+ add_check_constraint :recurrence_rules,+ "day_of_month IS NULL OR (day_of_month BETWEEN -1 AND 31 AND day_of_month <> 0)",+ name: "chk_recurrence_rules_day_of_month_range"+ add_check_constraint :recurrence_rules, "weekday IS NULL OR weekday BETWEEN 0 AND 6",+ name: "chk_recurrence_rules_weekday_range"+ add_check_constraint :recurrence_rules,+ "weekday_ordinal IS NULL OR (weekday_ordinal BETWEEN -1 AND 5 AND weekday_ordinal <> 0)",+ name: "chk_recurrence_rules_weekday_ordinal_range"+ add_check_constraint :recurrence_rules, "month_of_year IS NULL OR month_of_year BETWEEN 1 AND 12",+ name: "chk_recurrence_rules_month_of_year_range"+ # An ordinal is meaningless without a weekday; a weekday without an ordinal+ # is legal only for weekly rules, which the model enforces (constraints+ # here stay shape-level so errors can carry messages).+ add_check_constraint :recurrence_rules,+ "weekday_ordinal IS NULL OR weekday IS NOT NULL",+ name: "chk_recurrence_rules_ordinal_requires_weekday"+ add_check_constraint :recurrence_rules,+ "NOT (day_of_month IS NOT NULL AND weekday IS NOT NULL)",+ name: "chk_recurrence_rules_single_day_spec"++ change_table :recurring_transactions, bulk: true do |t|+ t.date :anchor_date+ t.string :end_mode, null: false, default: "never"+ t.date :end_on+ t.integer :end_after_count+ t.string :weekend_adjust, null: false, default: "none"+ t.string :holiday_calendar+ end++ # Every existing series is monthly on expected_day_of_month; give each an+ # explicit rule saying exactly that, anchored on its last occurrence. A+ # series with zero rules stays legal (Schedule synthesizes the implicit+ # monthly rule), so this backfill is a normalization, not a requirement.+ execute <<~SQL+ INSERT INTO recurrence_rules (id, recurring_transaction_id, frequency, interval, day_of_month, position, created_at, updated_at)+ SELECT gen_random_uuid(), id, 'monthly', 1, expected_day_of_month, 0, NOW(), NOW()+ FROM recurring_transactions+ SQL++ execute <<~SQL+ UPDATE recurring_transactions SET anchor_date = last_occurrence_date WHERE anchor_date IS NULL+ SQL++ # -- Bill attributes on the series ---------------------------------------+ change_table :recurring_transactions, bulk: true do |t|+ # Classification & linkage+ t.string :bill_type, null: false, default: "bill"+ t.references :category, type: :uuid, foreign_key: { on_delete: :nullify }, index: true+ t.uuid :replaced_by_id++ # Amount semantics+ t.string :amount_strategy, null: false, default: "fixed"+ t.decimal :amount_tolerance_pct, precision: 5, scale: 2, null: false, default: 7.5++ # Per-bill knobs (NULL = app default)+ t.integer :notify_days_before+ t.integer :upcoming_window_days+ t.integer :overdue_grace_days+ t.integer :match_days_early, null: false, default: 2+ t.integer :match_days_late, null: false, default: 7++ # Subscription lifecycle+ t.date :renews_on+ t.date :trial_ends_on+ t.date :cancelled_on++ # Matcher memory (transparent, user-visible)+ t.jsonb :matcher_hints, null: false, default: {}+ end++ add_foreign_key :recurring_transactions, :recurring_transactions,+ column: :replaced_by_id, on_delete: :nullify++ # A transfer-shaped series is a payment obligation between two of the+ # user's own accounts (credit-card payment, loan payment); income is an+ # inflow (expenses are stored positive); everything else is a bill.+ execute <<~SQL+ UPDATE recurring_transactions+ SET bill_type = CASE+ WHEN destination_account_id IS NOT NULL THEN 'transfer'+ WHEN amount < 0 THEN 'income'+ ELSE 'bill'+ END+ SQL++ # -- Identity index rework ------------------------------------------------+ # The four identity indexes included `amount`, so any price change forked+ # the series into a second row instead of updating the first --+ # auto-detection is amount-scoped by construction. Identity becomes+ # (family, account, [destination], merchant|name, currency, dedup_scope):+ # price changes update `amount` freely, and the rare LEGITIMATE second+ # series for one identifier (three Twitch tiers) carries a discriminator+ # in dedup_scope instead.+ add_column :recurring_transactions, :dedup_scope, :string, null: false, default: ""++ stamp_existing_price_forks++ remove_index :recurring_transactions, name: "idx_recurring_txns_acct_merchant"+ remove_index :recurring_transactions, name: "idx_recurring_txns_acct_name"+ remove_index :recurring_transactions, name: "idx_recurring_txns_pair_merchant"+ remove_index :recurring_transactions, name: "idx_recurring_txns_pair_name"++ add_index :recurring_transactions,+ [ :family_id, :account_id, :merchant_id, :amount, :currency, :dedup_scope ],+ unique: true, name: "idx_recurring_txns_acct_merchant",+ where: "merchant_id IS NOT NULL AND destination_account_id IS NULL"+ add_index :recurring_transactions,+ [ :family_id, :account_id, :name, :amount, :currency, :dedup_scope ],+ unique: true, name: "idx_recurring_txns_acct_name",+ where: "name IS NOT NULL AND merchant_id IS NULL AND destination_account_id IS NULL"+ add_index :recurring_transactions,+ [ :family_id, :account_id, :destination_account_id, :merchant_id, :amount, :currency, :dedup_scope ],+ unique: true, name: "idx_recurring_txns_pair_merchant",+ where: "destination_account_id IS NOT NULL AND merchant_id IS NOT NULL"+ add_index :recurring_transactions,+ [ :family_id, :account_id, :destination_account_id, :name, :amount, :currency, :dedup_scope ],+ unique: true, name: "idx_recurring_txns_pair_name",+ where: "destination_account_id IS NOT NULL AND name IS NOT NULL AND merchant_id IS NULL"++ # Session imports resolve cross-chunk references through persisted source+ # mappings, and occurrences joined that contract when allocations started+ # arriving in later chunks than the cycles they pay.+ remove_check_constraint :import_source_mappings, name: "chk_import_source_mappings_source_type"+ add_check_constraint :import_source_mappings,+ "source_type IN ('Account', 'Category', 'Tag', 'Merchant', 'RecurringTransaction', 'RecurringOccurrence', 'Transaction', 'Budget', 'Security', 'Rule')",+ name: "chk_import_source_mappings_source_type"+ remove_check_constraint :import_source_mappings, name: "chk_import_source_mappings_target_type"+ add_check_constraint :import_source_mappings,+ "target_type IN ('Account', 'Category', 'Tag', 'Merchant', 'RecurringTransaction', 'RecurringOccurrence', 'Transaction', 'Budget', 'Security', 'Rule')",+ name: "chk_import_source_mappings_target_type"++ # -- Occurrences, allocations, rejections, price history -----------------+ # One row per expected obligation instance. Materialized only inside a+ # rolling window or when carrying state; closed rows are immutable+ # history that survives any edit to the series definition.+ create_table :recurring_occurrences, id: :uuid do |t|+ t.references :recurring_transaction, type: :uuid, null: false,+ foreign_key: { on_delete: :cascade }, index: false+ t.references :family, type: :uuid, null: false,+ foreign_key: { on_delete: :cascade }, index: false+ t.date :original_due_on, null: false+ t.date :due_on, null: false+ t.string :currency, null: false+ t.decimal :expected_amount, precision: 19, scale: 4+ t.string :status, null: false, default: "scheduled"+ t.date :snoozed_until+ t.datetime :closed_at+ t.text :notes+ t.string :closed_source++ t.timestamps+ end++ add_index :recurring_occurrences, [ :recurring_transaction_id, :original_due_on ],+ unique: true, name: "idx_recurring_occurrences_identity"+ add_index :recurring_occurrences, [ :family_id, :status, :due_on ]+ add_index :recurring_occurrences, [ :family_id, :due_on ]+ add_check_constraint :recurring_occurrences,+ "(status = 'scheduled') = (closed_at IS NULL)",+ name: "chk_recurring_occurrences_closed_state"++ # Links payments to occurrences with an amount, which is what makes+ # partial payments first-class: several allocations sum toward one+ # obligation, and one entry can cover several. entry_id is nullable from+ # birth for payments recorded without a bank transaction, and nullified+ # on entry deletion so the payment record survives.+ create_table :recurring_allocations, id: :uuid do |t|+ t.references :recurring_occurrence, type: :uuid, null: false,+ foreign_key: { on_delete: :cascade }, index: false+ t.references :entry, type: :uuid, foreign_key: { on_delete: :nullify }, index: true+ t.decimal :allocated_amount, precision: 19, scale: 4, null: false+ t.string :currency, null: false+ t.decimal :source_amount, precision: 19, scale: 4+ t.string :source_currency+ t.string :state, null: false, default: "confirmed"+ t.string :source, null: false+ t.decimal :match_confidence, precision: 5, scale: 4+ t.jsonb :match_signals, null: false, default: {}+ t.date :paid_on++ t.timestamps+ end++ add_index :recurring_allocations, [ :recurring_occurrence_id, :entry_id ],+ unique: true, where: "entry_id IS NOT NULL",+ name: "idx_recurring_allocations_entry_once"+ add_index :recurring_allocations, :recurring_occurrence_id+ add_check_constraint :recurring_allocations, "allocated_amount > 0",+ name: "chk_recurring_allocations_amount_positive"++ # A rejected (series, entry) pair is never suggested again.+ create_table :recurring_match_rejections, id: :uuid do |t|+ t.references :recurring_transaction, type: :uuid, null: false,+ foreign_key: { on_delete: :cascade }, index: false+ t.references :entry, type: :uuid, null: false,+ foreign_key: { on_delete: :cascade }, index: false++ t.timestamps+ end++ add_index :recurring_match_rejections, [ :recurring_transaction_id, :entry_id ],+ unique: true, name: "idx_recurring_match_rejections_pair"++ # Price history per series, feeding subscription intelligence.+ create_table :recurring_price_changes, id: :uuid do |t|+ t.references :recurring_transaction, type: :uuid, null: false,+ foreign_key: { on_delete: :cascade }, index: false+ t.date :effective_on, null: false+ t.decimal :previous_amount, precision: 19, scale: 4, null: false+ t.decimal :new_amount, precision: 19, scale: 4, null: false+ t.string :currency, null: false+ t.string :source, null: false+ t.references :entry, type: :uuid, foreign_key: { on_delete: :nullify }, index: false++ t.timestamps+ end++ add_index :recurring_price_changes, [ :recurring_transaction_id, :effective_on ],+ unique: true, name: "idx_recurring_price_changes_identity"++ # -- Enum and currency invariants, in the database ------------------------+ # These invariants were enforced only by Rails: an enum assignment raises+ # in Ruby, and "an allocation is denominated in its occurrence's currency"+ # was a model validation. Neither survives insert_all, a rake task or a+ # console session, and this is a ledger. No values change.+ add_check_constraint :recurring_occurrences,+ "status IN ('scheduled', 'paid', 'skipped', 'missed')",+ name: "chk_recurring_occurrences_status"++ add_check_constraint :recurring_occurrences,+ "closed_source IS NULL OR closed_source IN ('auto', 'user')",+ name: "chk_recurring_occurrences_closed_source"++ add_check_constraint :recurring_allocations,+ "state IN ('suggested', 'confirmed')",+ name: "chk_recurring_allocations_state"++ add_check_constraint :recurring_allocations,+ "source IN ('auto_matched', 'user_confirmed', 'user_created')",+ name: "chk_recurring_allocations_source"++ # Currency equality spans two tables, so a CHECK cannot express it. A+ # composite foreign key can: the pair (occurrence, currency) must exist on+ # the occurrence itself, which makes a mismatch unrepresentable rather+ # than merely invalid.+ execute <<~SQL+ UPDATE recurring_allocations a+ SET currency = o.currency+ FROM recurring_occurrences o+ WHERE o.id = a.recurring_occurrence_id+ AND a.currency IS DISTINCT FROM o.currency+ SQL++ add_index :recurring_occurrences, [ :id, :currency ],+ unique: true, name: "idx_recurring_occurrences_id_currency"++ execute <<~SQL+ ALTER TABLE recurring_allocations+ ADD CONSTRAINT fk_recurring_allocations_currency_matches_occurrence+ FOREIGN KEY (recurring_occurrence_id, currency)+ REFERENCES recurring_occurrences (id, currency)+ ON DELETE CASCADE+ SQL++ # -- iCal feed token on the family ----------------------------------------+ add_column :families, :bills_feed_token, :string+ add_index :families, :bills_feed_token, unique: true++ # -- Entry-side delete performance ----------------------------------------+ # Entry deletes enforce cascade/nullify on these tables; without a+ # leading entry_id index each delete walks the whole table.+ add_index :recurring_match_rejections, :entry_id+ add_index :recurring_price_changes, :entry_id++ # The frequency enum raises only in Ruby; a row written past the model+ # (insert_all, a rake task, a console session) could carry a frequency the+ # schedule engine cannot generate occurrences for.+ add_check_constraint :recurrence_rules,+ "frequency IN ('weekly', 'monthly', 'yearly')",+ name: "chk_recurrence_rules_frequency"+ end++ def down+ remove_check_constraint :recurrence_rules, name: "chk_recurrence_rules_frequency"++ remove_index :recurring_price_changes, :entry_id+ remove_index :recurring_match_rejections, :entry_id++ remove_index :families, :bills_feed_token+ remove_column :families, :bills_feed_token++ execute <<~SQL+ ALTER TABLE recurring_allocations+ DROP CONSTRAINT IF EXISTS fk_recurring_allocations_currency_matches_occurrence+ SQL+ remove_index :recurring_occurrences, name: "idx_recurring_occurrences_id_currency"+ remove_check_constraint :recurring_allocations, name: "chk_recurring_allocations_source"+ remove_check_constraint :recurring_allocations, name: "chk_recurring_allocations_state"+ remove_check_constraint :recurring_occurrences, name: "chk_recurring_occurrences_closed_source"+ remove_check_constraint :recurring_occurrences, name: "chk_recurring_occurrences_status"++ drop_table :recurring_price_changes+ drop_table :recurring_match_rejections+ drop_table :recurring_allocations+ drop_table :recurring_occurrences++ remove_check_constraint :import_source_mappings, name: "chk_import_source_mappings_source_type"+ add_check_constraint :import_source_mappings,+ "source_type IN ('Account', 'Category', 'Tag', 'Merchant', 'RecurringTransaction', 'Transaction', 'Budget', 'Security', 'Rule')",+ name: "chk_import_source_mappings_source_type"+ remove_check_constraint :import_source_mappings, name: "chk_import_source_mappings_target_type"+ add_check_constraint :import_source_mappings,+ "target_type IN ('Account', 'Category', 'Tag', 'Merchant', 'RecurringTransaction', 'Transaction', 'Budget', 'Security', 'Rule')",+ name: "chk_import_source_mappings_target_type"++ # The up migration widens the uniqueness key with dedup_scope, so rows that+ # differ only in scope, deliberate price forks, can exist by the time anyone+ # rolls back. Recreating the narrower indexes would then fail mid-migration,+ # or force a choice about which fork to destroy. Refusing with a clear+ # message beats either. A database that never grew such rows rolls back+ # exactly as before.+ # One check per restored index, mirroring its exact columns and predicate.+ # A single broad grouping missed pairs the narrower merchant indexes would+ # still reject, and the failure would land after the bills tables were+ # already dropped.+ # account_id is the one nullable indexed column, and the indexes treat+ # NULLs as distinct: two accountless rows never collide, so grouping them+ # here would refuse a rollback PostgreSQL can perform.+ collision_checks = [+ [ "family_id, account_id, merchant_id, amount, currency",+ "account_id IS NOT NULL AND merchant_id IS NOT NULL AND destination_account_id IS NULL" ],+ [ "family_id, account_id, name, amount, currency",+ "account_id IS NOT NULL AND name IS NOT NULL AND merchant_id IS NULL AND destination_account_id IS NULL" ],+ [ "family_id, account_id, destination_account_id, merchant_id, amount, currency",+ "account_id IS NOT NULL AND destination_account_id IS NOT NULL AND merchant_id IS NOT NULL" ],+ [ "family_id, account_id, destination_account_id, name, amount, currency",+ "account_id IS NOT NULL AND destination_account_id IS NOT NULL AND name IS NOT NULL AND merchant_id IS NULL" ]+ ]+ forked = collision_checks.any? do |columns, predicate|+ ActiveModel::Type::Boolean.new.cast(select_value(<<~SQL))+ SELECT EXISTS (+ SELECT 1 FROM recurring_transactions+ WHERE #{predicate}+ GROUP BY #{columns}+ HAVING COUNT(*) > 1+ )+ SQL+ end+ if forked+ raise ActiveRecord::IrreversibleMigration,+ "recurring_transactions holds rows distinguished only by dedup_scope " \+ "(price-forked series). The pre-bills unique indexes cannot be recreated " \+ "without losing one of each pair. Remove or merge the forked series first."+ end++ remove_index :recurring_transactions, name: "idx_recurring_txns_acct_merchant"+ remove_index :recurring_transactions, name: "idx_recurring_txns_acct_name"+ remove_index :recurring_transactions, name: "idx_recurring_txns_pair_merchant"+ remove_index :recurring_transactions, name: "idx_recurring_txns_pair_name"++ add_index :recurring_transactions,+ [ :family_id, :account_id, :merchant_id, :amount, :currency ],+ unique: true, name: "idx_recurring_txns_acct_merchant",+ where: "merchant_id IS NOT NULL AND destination_account_id IS NULL"+ add_index :recurring_transactions,+ [ :family_id, :account_id, :name, :amount, :currency ],+ unique: true, name: "idx_recurring_txns_acct_name",+ where: "name IS NOT NULL AND merchant_id IS NULL AND destination_account_id IS NULL"+ add_index :recurring_transactions,+ [ :family_id, :account_id, :destination_account_id, :merchant_id, :amount, :currency ],+ unique: true, name: "idx_recurring_txns_pair_merchant",+ where: "destination_account_id IS NOT NULL AND merchant_id IS NOT NULL"+ add_index :recurring_transactions,+ [ :family_id, :account_id, :destination_account_id, :name, :amount, :currency ],+ unique: true, name: "idx_recurring_txns_pair_name",+ where: "destination_account_id IS NOT NULL AND name IS NOT NULL AND merchant_id IS NULL"++ remove_column :recurring_transactions, :dedup_scope++ remove_foreign_key :recurring_transactions, column: :replaced_by_id+ change_table :recurring_transactions, bulk: true do |t|+ t.remove :bill_type, :category_id, :replaced_by_id, :amount_strategy, :amount_tolerance_pct,+ :notify_days_before, :upcoming_window_days, :overdue_grace_days,+ :match_days_early, :match_days_late, :renews_on, :trial_ends_on, :cancelled_on,+ :matcher_hints+ end++ change_table :recurring_transactions, bulk: true do |t|+ t.remove :anchor_date, :end_mode, :end_on, :end_after_count, :weekend_adjust, :holiday_calendar+ end+ drop_table :recurrence_rules++ change_table :recurring_transactions, bulk: true do |t|+ t.remove :autopay, :notes, :payment_url+ end+ end++ private+ # Rows that collide once amount leaves the identity are either price-change+ # forks or genuinely distinct series for one identifier. The migration+ # cannot tell them apart, so it keeps the newest row unscoped and stamps+ # the rest with their amount as a discriminator -- preserving every row and+ # the old identity semantics exactly -- and logs each group for a one-time+ # human review.+ def stamp_existing_price_forks+ rows = select_all(<<~SQL).to_a+ SELECT id, family_id, account_id, destination_account_id, merchant_id, name, currency,+ amount, updated_at+ FROM recurring_transactions+ ORDER BY updated_at DESC+ SQL++ groups = rows.group_by do |row|+ [ row["family_id"], row["account_id"], row["destination_account_id"],+ row["merchant_id"] || "name:#{row['name']}", row["currency"] ]+ end++ groups.each_value do |group|+ next if group.size == 1++ keeper, *rest = group+ say "dedup_scope: keeping #{keeper['id']} (#{keeper['amount']}) unscoped; stamping #{rest.size} sibling(s)"++ rest.each do |row|+ scope = BigDecimal(row["amount"].to_s).to_s("F")+ say " #{row['id']} amount=#{row['amount']} -> dedup_scope=#{scope}"+ update("UPDATE recurring_transactions SET dedup_scope = #{quote(scope)} WHERE id = #{quote(row['id'])}")+ end+ end+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 40f629525b..307e0f13fb 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -777,6 +777,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_08_26_090000) docreate_table "families", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|t.string "assistant_type", default: "builtin", null: falset.boolean "auto_sync_on_login", default: true, null: false+ t.string "bills_feed_token"t.string "country", default: "US"t.datetime "created_at", null: falset.string "currency", default: "USD"@@ -799,6 +800,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_08_26_090000) dot.string "timezone"t.datetime "updated_at", null: falset.string "vector_store_id"+ t.index ["bills_feed_token"], name: "index_families_on_bills_feed_token", unique: truet.check_constraint "default_account_sharing::text = ANY (ARRAY['shared'::character varying::text, 'private'::character varying::text])", name: "chk_families_default_account_sharing"t.check_constraint "month_start_day >= 1 AND month_start_day <= 28", name: "month_start_day_range"end@@ -1069,8 +1071,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_08_26_090000) dot.check_constraint "btrim(source_id::text) <> ''::text", name: "chk_import_source_mappings_source_id_present"t.check_constraint "btrim(source_type::text) <> ''::text", name: "chk_import_source_mappings_source_type_present"t.check_constraint "btrim(target_type::text) <> ''::text", name: "chk_import_source_mappings_target_type_present"- t.check_constraint "source_type::text = ANY (ARRAY['Account'::character varying::text, 'Category'::character varying::text, 'Tag'::character varying::text, 'Merchant'::character varying::text, 'RecurringTransaction'::character varying::text, 'Transaction'::character varying::text, 'Budget'::character varying::text, 'Security'::character varying::text, 'Rule'::character varying::text])", name: "chk_import_source_mappings_source_type"- t.check_constraint "target_type::text = ANY (ARRAY['Account'::character varying::text, 'Category'::character varying::text, 'Tag'::character varying::text, 'Merchant'::character varying::text, 'RecurringTransaction'::character varying::text, 'Transaction'::character varying::text, 'Budget'::character varying::text, 'Security'::character varying::text, 'Rule'::character varying::text])", name: "chk_import_source_mappings_target_type"+ t.check_constraint "source_type::text = ANY (ARRAY['Account'::character varying, 'Category'::character varying, 'Tag'::character varying, 'Merchant'::character varying, 'RecurringTransaction'::character varying, 'RecurringOccurrence'::character varying, 'Transaction'::character varying, 'Budget'::character varying, 'Security'::character varying, 'Rule'::character varying]::text[])", name: "chk_import_source_mappings_source_type"+ t.check_constraint "target_type::text = ANY (ARRAY['Account'::character varying, 'Category'::character varying, 'Tag'::character varying, 'Merchant'::character varying, 'RecurringTransaction'::character varying, 'RecurringOccurrence'::character varying, 'Transaction'::character varying, 'Budget'::character varying, 'Security'::character varying, 'Rule'::character varying]::text[])", name: "chk_import_source_mappings_target_type"endcreate_table "imports", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|@@ -1702,31 +1704,146 @@ ActiveRecord::Schema[8.1].define(version: 2026_08_26_090000) dot.index ["status"], name: "index_questrade_items_on_status"end+ create_table "recurrence_rules", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.datetime "created_at", null: false+ t.integer "day_of_month"+ t.string "frequency", null: false+ t.integer "interval", default: 1, null: false+ t.integer "month_of_year"+ t.integer "position", default: 0, null: false+ t.uuid "recurring_transaction_id", null: false+ t.datetime "updated_at", null: false+ t.integer "weekday"+ t.integer "weekday_ordinal"+ t.index ["recurring_transaction_id", "position"], name: "idx_on_recurring_transaction_id_position_62f0900d95", unique: true+ t.check_constraint "NOT (day_of_month IS NOT NULL AND weekday IS NOT NULL)", name: "chk_recurrence_rules_single_day_spec"+ t.check_constraint "\"interval\" > 0", name: "chk_recurrence_rules_interval_positive"+ t.check_constraint "day_of_month IS NULL OR day_of_month >= '-1'::integer AND day_of_month <= 31 AND day_of_month <> 0", name: "chk_recurrence_rules_day_of_month_range"+ t.check_constraint "frequency::text = ANY (ARRAY['weekly'::character varying, 'monthly'::character varying, 'yearly'::character varying]::text[])", name: "chk_recurrence_rules_frequency"+ t.check_constraint "month_of_year IS NULL OR month_of_year >= 1 AND month_of_year <= 12", name: "chk_recurrence_rules_month_of_year_range"+ t.check_constraint "weekday IS NULL OR weekday >= 0 AND weekday <= 6", name: "chk_recurrence_rules_weekday_range"+ t.check_constraint "weekday_ordinal IS NULL OR weekday IS NOT NULL", name: "chk_recurrence_rules_ordinal_requires_weekday"+ t.check_constraint "weekday_ordinal IS NULL OR weekday_ordinal >= '-1'::integer AND weekday_ordinal <= 5 AND weekday_ordinal <> 0", name: "chk_recurrence_rules_weekday_ordinal_range"+ end++ create_table "recurring_allocations", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.decimal "allocated_amount", precision: 19, scale: 4, null: false+ t.datetime "created_at", null: false+ t.string "currency", null: false+ t.uuid "entry_id"+ t.decimal "match_confidence", precision: 5, scale: 4+ t.jsonb "match_signals", default: {}, null: false+ t.date "paid_on"+ t.uuid "recurring_occurrence_id", null: false+ t.string "source", null: false+ t.decimal "source_amount", precision: 19, scale: 4+ t.string "source_currency"+ t.string "state", default: "confirmed", null: false+ t.datetime "updated_at", null: false+ t.index ["entry_id"], name: "index_recurring_allocations_on_entry_id"+ t.index ["recurring_occurrence_id", "entry_id"], name: "idx_recurring_allocations_entry_once", unique: true, where: "(entry_id IS NOT NULL)"+ t.index ["recurring_occurrence_id"], name: "index_recurring_allocations_on_recurring_occurrence_id"+ t.check_constraint "allocated_amount > 0::numeric", name: "chk_recurring_allocations_amount_positive"+ t.check_constraint "source::text = ANY (ARRAY['auto_matched'::character varying, 'user_confirmed'::character varying, 'user_created'::character varying]::text[])", name: "chk_recurring_allocations_source"+ t.check_constraint "state::text = ANY (ARRAY['suggested'::character varying, 'confirmed'::character varying]::text[])", name: "chk_recurring_allocations_state"+ end++ create_table "recurring_match_rejections", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.datetime "created_at", null: false+ t.uuid "entry_id", null: false+ t.uuid "recurring_transaction_id", null: false+ t.datetime "updated_at", null: false+ t.index ["entry_id"], name: "index_recurring_match_rejections_on_entry_id"+ t.index ["recurring_transaction_id", "entry_id"], name: "idx_recurring_match_rejections_pair", unique: true+ end++ create_table "recurring_occurrences", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.datetime "closed_at"+ t.string "closed_source"+ t.datetime "created_at", null: false+ t.string "currency", null: false+ t.date "due_on", null: false+ t.decimal "expected_amount", precision: 19, scale: 4+ t.uuid "family_id", null: false+ t.text "notes"+ t.date "original_due_on", null: false+ t.uuid "recurring_transaction_id", null: false+ t.date "snoozed_until"+ t.string "status", default: "scheduled", null: false+ t.datetime "updated_at", null: false+ t.index ["family_id", "due_on"], name: "index_recurring_occurrences_on_family_id_and_due_on"+ t.index ["family_id", "status", "due_on"], name: "index_recurring_occurrences_on_family_id_and_status_and_due_on"+ t.index ["id", "currency"], name: "idx_recurring_occurrences_id_currency", unique: true+ t.index ["recurring_transaction_id", "original_due_on"], name: "idx_recurring_occurrences_identity", unique: true+ t.check_constraint "(status::text = 'scheduled'::text) = (closed_at IS NULL)", name: "chk_recurring_occurrences_closed_state"+ t.check_constraint "closed_source IS NULL OR (closed_source::text = ANY (ARRAY['auto'::character varying, 'user'::character varying]::text[]))", name: "chk_recurring_occurrences_closed_source"+ t.check_constraint "status::text = ANY (ARRAY['scheduled'::character varying, 'paid'::character varying, 'skipped'::character varying, 'missed'::character varying]::text[])", name: "chk_recurring_occurrences_status"+ end++ create_table "recurring_price_changes", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.datetime "created_at", null: false+ t.string "currency", null: false+ t.date "effective_on", null: false+ t.uuid "entry_id"+ t.decimal "new_amount", precision: 19, scale: 4, null: false+ t.decimal "previous_amount", precision: 19, scale: 4, null: false+ t.uuid "recurring_transaction_id", null: false+ t.string "source", null: false+ t.datetime "updated_at", null: false+ t.index ["entry_id"], name: "index_recurring_price_changes_on_entry_id"+ t.index ["recurring_transaction_id", "effective_on"], name: "idx_recurring_price_changes_identity", unique: true+ end+create_table "recurring_transactions", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|t.uuid "account_id"t.decimal "amount", precision: 19, scale: 4, null: false+ t.string "amount_strategy", default: "fixed", null: false+ t.decimal "amount_tolerance_pct", precision: 5, scale: 2, default: "7.5", null: false+ t.date "anchor_date"+ t.boolean "autopay", default: false, null: false+ t.string "bill_type", default: "bill", null: false+ t.date "cancelled_on"+ t.uuid "category_id"t.datetime "created_at", null: falset.string "currency", null: false+ t.string "dedup_scope", default: "", null: falset.uuid "destination_account_id"+ t.integer "end_after_count"+ t.string "end_mode", default: "never", null: false+ t.date "end_on"t.decimal "expected_amount_avg", precision: 19, scale: 4t.decimal "expected_amount_max", precision: 19, scale: 4t.decimal "expected_amount_min", precision: 19, scale: 4t.integer "expected_day_of_month", null: falset.uuid "family_id", null: false+ t.string "holiday_calendar"t.date "last_occurrence_date", null: falset.boolean "manual", default: false, null: false+ t.integer "match_days_early", default: 2, null: false+ t.integer "match_days_late", default: 7, null: false+ t.jsonb "matcher_hints", default: {}, null: falset.uuid "merchant_id"t.string "name"t.date "next_expected_date", null: false+ t.text "notes"+ t.integer "notify_days_before"t.integer "occurrence_count", default: 0, null: false+ t.integer "overdue_grace_days"+ t.string "payment_url"+ t.date "renews_on"+ t.uuid "replaced_by_id"t.string "status", default: "active", null: false+ t.date "trial_ends_on"+ t.integer "upcoming_window_days"t.datetime "updated_at", null: false+ t.string "weekend_adjust", default: "none", null: falset.index ["account_id"], name: "index_recurring_transactions_on_account_id"+ t.index ["category_id"], name: "index_recurring_transactions_on_category_id"t.index ["destination_account_id"], name: "index_recurring_transactions_on_destination_account_id"- t.index ["family_id", "account_id", "destination_account_id", "merchant_id", "amount", "currency"], name: "idx_recurring_txns_pair_merchant", unique: true, where: "((destination_account_id IS NOT NULL) AND (merchant_id IS NOT NULL))"- t.index ["family_id", "account_id", "destination_account_id", "name", "amount", "currency"], name: "idx_recurring_txns_pair_name", unique: true, where: "((destination_account_id IS NOT NULL) AND (name IS NOT NULL) AND (merchant_id IS NULL))"- t.index ["family_id", "account_id", "merchant_id", "amount", "currency"], name: "idx_recurring_txns_acct_merchant", unique: true, where: "((merchant_id IS NOT NULL) AND (destination_account_id IS NULL))"- t.index ["family_id", "account_id", "name", "amount", "currency"], name: "idx_recurring_txns_acct_name", unique: true, where: "((name IS NOT NULL) AND (merchant_id IS NULL) AND (destination_account_id IS NULL))"+ t.index ["family_id", "account_id", "destination_account_id", "merchant_id", "amount", "currency", "dedup_scope"], name: "idx_recurring_txns_pair_merchant", unique: true, where: "((destination_account_id IS NOT NULL) AND (merchant_id IS NOT NULL))"+ t.index ["family_id", "account_id", "destination_account_id", "name", "amount", "currency", "dedup_scope"], name: "idx_recurring_txns_pair_name", unique: true, where: "((destination_account_id IS NOT NULL) AND (name IS NOT NULL) AND (merchant_id IS NULL))"+ t.index ["family_id", "account_id", "merchant_id", "amount", "currency", "dedup_scope"], name: "idx_recurring_txns_acct_merchant", unique: true, where: "((merchant_id IS NOT NULL) AND (destination_account_id IS NULL))"+ t.index ["family_id", "account_id", "name", "amount", "currency", "dedup_scope"], name: "idx_recurring_txns_acct_name", unique: true, where: "((name IS NOT NULL) AND (merchant_id IS NULL) AND (destination_account_id IS NULL))"t.index ["family_id", "status"], name: "index_recurring_transactions_on_family_id_and_status"t.index ["family_id"], name: "index_recurring_transactions_on_family_id"t.index ["merchant_id"], name: "index_recurring_transactions_on_merchant_id"@@ -2524,10 +2641,22 @@ ActiveRecord::Schema[8.1].define(version: 2026_08_26_090000) doadd_foreign_key "push_subscriptions", "users"add_foreign_key "questrade_accounts", "questrade_items"add_foreign_key "questrade_items", "families"+ add_foreign_key "recurrence_rules", "recurring_transactions", on_delete: :cascade+ add_foreign_key "recurring_allocations", "entries", on_delete: :nullify+ add_foreign_key "recurring_allocations", "recurring_occurrences", column: ["recurring_occurrence_id", "currency"], primary_key: ["id", "currency"], name: "fk_recurring_allocations_currency_matches_occurrence", on_delete: :cascade+ add_foreign_key "recurring_allocations", "recurring_occurrences", on_delete: :cascade+ add_foreign_key "recurring_match_rejections", "entries", on_delete: :cascade+ add_foreign_key "recurring_match_rejections", "recurring_transactions", on_delete: :cascade+ add_foreign_key "recurring_occurrences", "families", on_delete: :cascade+ add_foreign_key "recurring_occurrences", "recurring_transactions", on_delete: :cascade+ add_foreign_key "recurring_price_changes", "entries", on_delete: :nullify+ add_foreign_key "recurring_price_changes", "recurring_transactions", on_delete: :cascadeadd_foreign_key "recurring_transactions", "accounts", column: "destination_account_id", on_delete: :cascadeadd_foreign_key "recurring_transactions", "accounts", on_delete: :cascade+ add_foreign_key "recurring_transactions", "categories", on_delete: :nullifyadd_foreign_key "recurring_transactions", "families"add_foreign_key "recurring_transactions", "merchants"+ add_foreign_key "recurring_transactions", "recurring_transactions", column: "replaced_by_id", on_delete: :nullifyadd_foreign_key "redbark_accounts", "redbark_items"add_foreign_key "redbark_items", "families"add_foreign_key "rejected_transfers", "transactions", column: "inflow_transaction_id", on_delete: :cascadediff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex dfcb33cc56..d10b4862a6 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -1444,8 +1444,11 @@ components:status:type: stringenum:+ - suggested- active+ - paused- inactive+ - endedoccurrence_count:type: integerminimum: 0@@ -1454,6 +1457,98 @@ components:nullable: truemanual:type: boolean+ payment_url:+ type: string+ nullable: true+ description: Link to the biller portal where this bill is paid. Only http+ and https are accepted; a bare host is stored as https.+ autopay:+ type: boolean+ description: Whether this bill pays itself automatically.+ notes:+ type: string+ nullable: true+ description: Free-text notes shown alongside the bill.+ bill_type:+ type: string+ enum:+ - bill+ - subscription+ - installment+ - income+ - transfer+ - other+ description: What kind of obligation this is.+ category_id:+ type: string+ format: uuid+ nullable: true+ anchor_date:+ type: string+ format: date+ nullable: true+ description: Reference occurrence that phases every-N cadences.+ weekend_adjust:+ type: string+ enum:+ - none+ - skip+ - before+ - after+ end_mode:+ type: string+ enum:+ - never+ - on_date+ - after_count+ end_on:+ type: string+ format: date+ nullable: true+ end_after_count:+ type: integer+ nullable: true+ renews_on:+ type: string+ format: date+ nullable: true+ trial_ends_on:+ type: string+ format: date+ nullable: true+ cancelled_on:+ type: string+ format: date+ nullable: true+ recurrence_rules:+ type: array+ description: Repetition patterns; multiple rows express semimonthly and+ similar multi-pattern cadences. Empty means legacy monthly on expected_day_of_month.+ items:+ type: object+ properties:+ frequency:+ type: string+ enum:+ - weekly+ - monthly+ - yearly+ interval:+ type: integer+ day_of_month:+ type: integer+ nullable: true+ description: "-1 means the last day of the month."+ weekday:+ type: integer+ nullable: true+ weekday_ordinal:+ type: integer+ nullable: true+ description: "-1 means the last such weekday."+ month_of_year:+ type: integer+ nullable: trueexpected_amount_min:type: stringnullable: true@@ -6154,6 +6249,18 @@ paths:minimum: 0manual:type: boolean+ payment_url:+ type: string+ nullable: true+ description: Link to the biller portal. Only http and https+ are accepted; a bare host is stored as https.+ autopay:+ type: boolean+ description: Whether this bill pays itself automatically.+ notes:+ type: string+ nullable: true+ description: Free-text notes shown alongside the bill.expected_amount_min:type: numbernullable: true@@ -6269,6 +6376,19 @@ paths:next_expected_date:type: stringformat: date+ payment_url:+ type: string+ nullable: true+ description: Link to the biller portal. Only http and https+ are accepted; a bare host is stored as https. Send an empty+ string to clear it.+ autopay:+ type: boolean+ description: Whether this bill pays itself automatically.+ notes:+ type: string+ nullable: true+ description: Free-text notes shown alongside the bill.required: truedelete:summary: Delete recurring transactiondiff --git a/lib/tasks/recurring_bills.rake b/lib/tasks/recurring_bills.rakenew file mode 100644index 0000000000..39a9ac2272--- /dev/null+++ b/lib/tasks/recurring_bills.rake@@ -0,0 +1,50 @@+namespace :recurring do+ desc "Backfill occurrence history and reconcile it against real entries (re-runnable). MONTHS defaults to 6."+ task :backfill_history, [ :months ] => :environment do |_task, args|+ months = (args[:months] || 6).to_i+ from = months.months.ago.to_date++ Family.find_each do |family|+ next if family.recurring_transactions_disabled?++ puts "#{family.id}: backfilling #{months} months"++ pruned = RecurringTransaction::HistoryBackfiller.new(family, months: months).run!++ closed = family.recurring_occurrences.paid.count+ puts "#{family.id}: #{closed} occurrences closed as paid, #{pruned} uncovered past occurrences pruned"+ end+ end+end++namespace :recurring do+ desc "One-shot classification of existing auto-detected series still on defaults (kind bill, no category)"+ task classify_existing: :environment do+ Family.find_each do |family|+ next if family.recurring_transactions_disabled?++ reclassified = 0+ family.recurring_transactions+ .where(manual: false, bill_type: "bill", category_id: nil)+ .find_each do |series|+ entries = series.matching_transactions.first(6)+ next if entries.empty?++ classification = RecurringTransaction::Classifier.classify(+ name: series.display_name, entries: entries, account: series.account+ )+ next if classification.bill_type == "bill" && classification.category_id.nil?++ series.update!(+ bill_type: classification.bill_type,+ category_id: classification.category_id,+ autopay: series.autopay || classification.autopay+ )+ reclassified += 1+ puts " #{series.display_name}: #{classification.bill_type}#{classification.category_id ? ' +category' : ''}"+ end++ puts "#{family.id}: #{reclassified} series classified"+ end+ end+enddiff --git a/spec/requests/api/v1/recurring_transactions_spec.rb b/spec/requests/api/v1/recurring_transactions_spec.rbindex aedfd0df1f..e27f28873a 100644--- a/spec/requests/api/v1/recurring_transactions_spec.rb+++ b/spec/requests/api/v1/recurring_transactions_spec.rb@@ -132,6 +132,9 @@ RSpec.describe 'API V1 Recurring Transactions', type: :request dostatus: { type: :string, enum: %w[active inactive] },occurrence_count: { type: :integer, minimum: 0 },manual: { type: :boolean },+ payment_url: { type: :string, nullable: true, description: 'Link to the biller portal. Only http and https are accepted; a bare host is stored as https.' },+ autopay: { type: :boolean, description: 'Whether this bill pays itself automatically.' },+ notes: { type: :string, nullable: true, description: 'Free-text notes shown alongside the bill.' },expected_amount_min: { type: :number, nullable: true },expected_amount_max: { type: :number, nullable: true },expected_amount_avg: { type: :number, nullable: true }@@ -314,7 +317,10 @@ RSpec.describe 'API V1 Recurring Transactions', type: :request doproperties: {status: { type: :string, enum: %w[active inactive] },expected_day_of_month: { type: :integer, minimum: 1, maximum: 31 },- next_expected_date: { type: :string, format: :date }+ next_expected_date: { type: :string, format: :date },+ payment_url: { type: :string, nullable: true, description: 'Link to the biller portal. Only http and https are accepted; a bare host is stored as https. Send an empty string to clear it.' },+ autopay: { type: :boolean, description: 'Whether this bill pays itself automatically.' },+ notes: { type: :string, nullable: true, description: 'Free-text notes shown alongside the bill.' }}}}diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rbindex f1d5e7ed9c..1e6d02cea4 100644--- a/spec/swagger_helper.rb+++ b/spec/swagger_helper.rb@@ -795,10 +795,38 @@ RSpec.configure do |config|expected_day_of_month: { type: :integer, minimum: 1, maximum: 31 },last_occurrence_date: { type: :string, format: :date },next_expected_date: { type: :string, format: :date },- status: { type: :string, enum: %w[active inactive] },+ status: { type: :string, enum: %w[suggested active paused inactive ended] },occurrence_count: { type: :integer, minimum: 0 },name: { type: :string, nullable: true },manual: { type: :boolean },+ payment_url: { type: :string, nullable: true, description: 'Link to the biller portal where this bill is paid. Only http and https are accepted; a bare host is stored as https.' },+ autopay: { type: :boolean, description: 'Whether this bill pays itself automatically.' },+ notes: { type: :string, nullable: true, description: 'Free-text notes shown alongside the bill.' },+ bill_type: { type: :string, enum: %w[bill subscription installment income transfer other], description: 'What kind of obligation this is.' },+ category_id: { type: :string, format: :uuid, nullable: true },+ anchor_date: { type: :string, format: :date, nullable: true, description: 'Reference occurrence that phases every-N cadences.' },+ weekend_adjust: { type: :string, enum: %w[none skip before after] },+ end_mode: { type: :string, enum: %w[never on_date after_count] },+ end_on: { type: :string, format: :date, nullable: true },+ end_after_count: { type: :integer, nullable: true },+ renews_on: { type: :string, format: :date, nullable: true },+ trial_ends_on: { type: :string, format: :date, nullable: true },+ cancelled_on: { type: :string, format: :date, nullable: true },+ recurrence_rules: {+ type: :array,+ description: 'Repetition patterns; multiple rows express semimonthly and similar multi-pattern cadences. Empty means legacy monthly on expected_day_of_month.',+ items: {+ type: :object,+ properties: {+ frequency: { type: :string, enum: %w[weekly monthly yearly] },+ interval: { type: :integer },+ day_of_month: { type: :integer, nullable: true, description: '-1 means the last day of the month.' },+ weekday: { type: :integer, nullable: true },+ weekday_ordinal: { type: :integer, nullable: true, description: '-1 means the last such weekday.' },+ month_of_year: { type: :integer, nullable: true }+ }+ }+ },expected_amount_min: { type: :string, nullable: true },expected_amount_min_cents: { type: :integer, nullable: true, description: 'Minimum expected amount in currency minor units' },expected_amount_max: { type: :string, nullable: true },diff --git a/test/controllers/api/v1/recurring_transactions_controller_test.rb b/test/controllers/api/v1/recurring_transactions_controller_test.rbindex f03f08639a..daa2c679f9 100644--- a/test/controllers/api/v1/recurring_transactions_controller_test.rb+++ b/test/controllers/api/v1/recurring_transactions_controller_test.rb@@ -330,6 +330,26 @@ class Api::V1::RecurringTransactionsControllerTest < ActionDispatch::Integrationassert_equal 16, response_data["expected_day_of_month"]end+ test "should update payment url and normalize a bare host" do+ patch api_v1_recurring_transaction_url(@recurring_transaction),+ params: { recurring_transaction: { payment_url: "pay.example.com/bill" } },+ headers: api_headers(@api_key)++ assert_response :success+ assert_equal "https://pay.example.com/bill", JSON.parse(response.body)["payment_url"]+ end++ # The API is a second door onto the same field, so the scheme allowlist has to hold+ # here too and not only in the web form.+ test "should reject a payment url with a non-http scheme" do+ patch api_v1_recurring_transaction_url(@recurring_transaction),+ params: { recurring_transaction: { payment_url: "javascript:alert(1)" } },+ headers: api_headers(@api_key)++ assert_response :unprocessable_entity+ assert_nil @recurring_transaction.reload.payment_url+ end+test "should require authentication when updating recurring transaction" dopatch api_v1_recurring_transaction_url(@recurring_transaction),params: { recurring_transaction: { status: "inactive" } }@@ -357,7 +377,7 @@ class Api::V1::RecurringTransactionsControllerTest < ActionDispatch::Integrationtest "should reject update with invalid status" dopatch api_v1_recurring_transaction_url(@recurring_transaction),- params: { recurring_transaction: { status: "paused" } },+ params: { recurring_transaction: { status: "bogus_status" } },headers: api_headers(@api_key)assert_response :unprocessable_entity@@ -365,6 +385,37 @@ class Api::V1::RecurringTransactionsControllerTest < ActionDispatch::Integrationassert_equal "validation_failed", response_data["error"]end+ # suggested, paused and ended are valid model statuses, but they are+ # lifecycle states the API does not document as writable and must refuse.+ test "should reject update with an undocumented model status" do+ %w[suggested paused ended].each do |status|+ patch api_v1_recurring_transaction_url(@recurring_transaction),+ params: { recurring_transaction: { status: status } },+ headers: api_headers(@api_key)++ assert_response :unprocessable_entity+ response_data = JSON.parse(response.body)+ assert_equal "validation_failed", response_data["error"]+ assert_equal "active", @recurring_transaction.reload.status,+ "#{status} must not be written through the API"+ end+ end++ test "should reject create with an undocumented model status" do+ params = valid_recurring_transaction_params.deep_dup+ params[:recurring_transaction][:status] = "suggested"++ assert_no_difference("@family.recurring_transactions.count") do+ post api_v1_recurring_transactions_url,+ params: params,+ headers: api_headers(@api_key)+ end++ assert_response :unprocessable_entity+ response_data = JSON.parse(response.body)+ assert_equal "validation_failed", response_data["error"]+ end+test "should reject update with nil status" dopatch api_v1_recurring_transaction_url(@recurring_transaction),params: { recurring_transaction: { status: nil } },diff --git a/test/models/budget_category_test.rb b/test/models/budget_category_test.rbindex 3031f0586c..2698b25307 100644--- a/test/models/budget_category_test.rb+++ b/test/models/budget_category_test.rb@@ -49,6 +49,72 @@ class BudgetCategoryTest < ActiveSupport::TestCase)end+ # A reservation that silently omits an obligation reads as money still free to+ # spend, so one with no rate is counted and reported instead of skipped.+ test "bills_reserved counts an obligation it cannot convert" do+ foreign = @family.recurring_transactions.create!(+ name: "Tokyo storage", account: accounts(:depository), amount: 50_000,+ currency: "JPY", bill_type: "bill", category_id: @parent_category.id,+ expected_day_of_month: 3, anchor_date: @budget.start_date,+ last_occurrence_date: @budget.start_date, next_expected_date: @budget.start_date,+ status: "active", manual: true+ )+ # Creating a series generates its own occurrences; clear them so this test+ # asserts against exactly one known row.+ foreign.recurring_occurrences.destroy_all+ foreign.recurring_occurrences.create!(+ family: @family, original_due_on: @budget.start_date + 3,+ due_on: @budget.start_date + 3, currency: "JPY", expected_amount: 50_000+ )+ assert_equal 0, ExchangeRate.where(from_currency: "JPY", to_currency: "USD").count,+ "the scenario depends on there being no rate to find"++ assert_equal 1, @parent_budget_category.bills_reserved_unconvertible_count,+ "the JPY obligation must be reported rather than dropped from the reservation"+ end++ # A foreign obligation is still owed out of this category, so it is converted+ # rather than skipped. The old behaviour reserved nothing for it at all.+ test "bills_reserved converts a foreign obligation it has a rate for" do+ # exchange_to defaults to today's rate, matching how every other bills+ # total converts.+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", rate: 1.1,+ date: Date.current)+ eur = @family.recurring_transactions.create!(+ name: "Berlin storage", account: accounts(:depository), amount: 100,+ currency: "EUR", bill_type: "bill", category_id: @parent_category.id,+ expected_day_of_month: 3, anchor_date: @budget.start_date,+ last_occurrence_date: @budget.start_date, next_expected_date: @budget.start_date,+ status: "active", manual: true+ )+ eur.recurring_occurrences.destroy_all+ eur.recurring_occurrences.create!(+ family: @family, original_due_on: @budget.start_date + 3,+ due_on: @budget.start_date + 3, currency: "EUR", expected_amount: 100+ )++ assert_equal 110, @parent_budget_category.bills_reserved.amount+ assert_equal 0, @parent_budget_category.bills_reserved_unconvertible_count+ end++ test "bills_reserved sums obligations in the budget currency" do+ bill = @family.recurring_transactions.create!(+ name: "Groceries plan", account: accounts(:depository), amount: 120,+ currency: "USD", bill_type: "bill", category_id: @parent_category.id,+ expected_day_of_month: 3, anchor_date: @budget.start_date,+ last_occurrence_date: @budget.start_date, next_expected_date: @budget.start_date,+ status: "active", manual: true+ )+ bill.recurring_occurrences.destroy_all+ bill.recurring_occurrences.create!(+ family: @family, original_due_on: @budget.start_date + 3,+ due_on: @budget.start_date + 3, currency: "USD", expected_amount: 120+ )++ assert_equal 120, @parent_budget_category.bills_reserved.amount+ assert_equal 0, @parent_budget_category.bills_reserved_unconvertible_count+ end+test "subcategory with zero budget inherits from parent" doassert @subcategory_inheriting_bc.inherits_parent_budget?refute @subcategory_with_limit_bc.inherits_parent_budget?diff --git a/test/models/family/data_exporter_test.rb b/test/models/family/data_exporter_test.rbindex cc981e3a41..938454a45e 100644--- a/test/models/family/data_exporter_test.rb+++ b/test/models/family/data_exporter_test.rb@@ -674,6 +674,7 @@ class Family::DataExporterTest < ActiveSupport::TestCasestatus: "active",occurrence_count: 6,manual: true,+ payment_url: "https://pay.example.com/internet",expected_amount_min: -95,expected_amount_max: -85,expected_amount_avg: -89.99@@ -695,6 +696,7 @@ class Family::DataExporterTest < ActiveSupport::TestCaseassert_equal "-89.99", BigDecimal(recurring_data["data"]["amount"].to_s).to_s("F")assert_equal "active", recurring_data["data"]["status"]assert_equal true, recurring_data["data"]["manual"]+ assert_equal "https://pay.example.com/internet", recurring_data["data"]["payment_url"]assert_not recurring_data["data"].key?("family_id")endenddiff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rbindex 3e3597872f..4648f1efe2 100644--- a/test/models/family/data_importer_test.rb+++ b/test/models/family/data_importer_test.rb@@ -530,6 +530,7 @@ class Family::DataImporterTest < ActiveSupport::TestCasestatus: "active",occurrence_count: 6,manual: true,+ payment_url: "https://pay.example.com/internet",expected_amount_min: "-95.00",expected_amount_max: "-85.00",expected_amount_avg: "-89.99"@@ -551,6 +552,7 @@ class Family::DataImporterTest < ActiveSupport::TestCaseassert_equal "active", recurring_transaction.statusassert_equal 6, recurring_transaction.occurrence_countassert_equal true, recurring_transaction.manual+ assert_equal "https://pay.example.com/internet", recurring_transaction.payment_urlassert_equal(-95.0, recurring_transaction.expected_amount_min.to_f)assert_equal(-85.0, recurring_transaction.expected_amount_max.to_f)assert_equal(-89.99, recurring_transaction.expected_amount_avg.to_f)@@ -665,7 +667,7 @@ class Family::DataImporterTest < ActiveSupport::TestCaseexpected_day_of_month: "8",last_occurrence_date: "2024-01-08",next_expected_date: "2024-02-08",- status: "paused",+ status: "bogus_status",occurrence_count: 2}}@@ -2320,9 +2322,217 @@ class Family::DataImporterTest < ActiveSupport::TestCaseassert_equal "Local Grocery", recurring_transaction.merchant.nameend+ # Everything below the series was silently absent from an export: a restored+ # bill kept its name and amount and lost its cadence, its payment history and+ # every setting that decides how it behaves.+ test "imports the bills subsystem, reattaching payments to their transactions" do+ importer = Family::DataImporter.new(@family, build_ndjson(bills_ndjson_records))+ importer.import!++ series = @family.recurring_transactions.sole+ assert_equal "bill", series.bill_type+ assert_equal 9.5, series.amount_tolerance_pct.to_f+ assert_equal "before", series.weekend_adjust+ assert_equal "2000", series.dedup_scope+ assert_equal [ "WATSON PROPERTY" ], series.matcher_hints["name_aliases"]++ rule = series.recurrence_rules.sole+ assert_equal "weekly", rule.frequency, "cadence must survive, not fall back to monthly"+ assert_equal 2, rule.interval++ occurrence = series.recurring_occurrences.find_by(original_due_on: Date.new(2026, 6, 9))+ assert occurrence.paid?+ assert_equal 2000, occurrence.expected_amount.to_f++ allocation = occurrence.allocations.sole+ assert_equal 2000, allocation.allocated_amount.to_f+ assert_equal "user_confirmed", allocation.source+ assert_not_nil allocation.entry, "the payment must reattach to the imported transaction"+ assert_equal 2000, allocation.entry.amount.to_f+ assert_equal Date.new(2026, 6, 9), allocation.entry.date+ end++ test "replaying a bills export changes nothing the second time" do+ records = bills_ndjson_records+ session = @family.import_sessions.create!+ Family::DataImporter.new(@family, build_ndjson(records), import_session: session).import!++ census = -> {+ [ RecurrenceRule.joins(:recurring_transaction).where(recurring_transactions: { family_id: @family.id }).count,+ RecurringOccurrence.where(family_id: @family.id).count,+ RecurringAllocation.joins(:recurring_occurrence).where(recurring_occurrences: { family_id: @family.id }).count ]+ }+ before = census.call++ # The replay contract is the session's: mappings persisted on the first+ # pass, so a fresh importer resolves every record to the row already+ # created instead of skipping or duplicating it.+ Family::DataImporter.new(@family, build_ndjson(records), import_session: session).import!++ assert_equal before, census.call+ end++ test "a closed occurrence exported without closed_at replays to the same timestamp" do+ records = bills_ndjson_records+ records.each { |record| record[:data].delete(:closed_at) if record[:type] == "RecurringOccurrence" }++ session = @family.import_sessions.create!+ Family::DataImporter.new(@family, build_ndjson(records), import_session: session).import!+ occurrence = @family.recurring_transactions.sole+ .recurring_occurrences.find_by!(original_due_on: Date.new(2026, 6, 9))+ first_stamp = occurrence.closed_at+ assert_not_nil first_stamp+ assert_equal Date.new(2026, 6, 9), first_stamp.to_date, "the stand-in derives from the due date"++ # A day later so a stand-in recomputed at import time would visibly move.+ travel 1.day do+ Family::DataImporter.new(@family, build_ndjson(records), import_session: session).import!+ end++ assert_equal first_stamp, occurrence.reload.closed_at,+ "an import-time stand-in would move the historical timestamp on every replay"+ end++ test "one incoherent recurrence rule row is skipped, not the whole import" do+ records = bills_ndjson_records+ records.each do |record|+ record[:data][:interval] = nil if record[:type] == "RecurrenceRule"+ end++ result = Family::DataImporter.new(@family, build_ndjson(records)).import!++ assert_equal 1, result.dig(:summary, "recurrence_rules", "skipped")+ assert_equal 1, @family.recurring_transactions.count,+ "the rest of the file must land even though one rule row was stale"+ end++ test "a hand-recorded allocation without a paid_on is skipped, not defaulted to today" do+ records = bills_ndjson_records+ records.each do |record|+ next unless record[:type] == "RecurringAllocation"++ record[:data].delete(:transaction_id)+ record[:data].delete(:paid_on)+ end++ result = Family::DataImporter.new(@family, build_ndjson(records)).import!++ occurrence = @family.recurring_transactions.sole+ .recurring_occurrences.find_by!(original_due_on: Date.new(2026, 6, 9))+ assert_equal 0, occurrence.allocations.count,+ "a defaulted paid_on would make every later replay insert a fresh copy"+ assert_equal 1, result.dig(:summary, "recurring_allocations", "skipped")+ end++ test "recurring records whose series never came across are counted as skipped" do+ ndjson = build_ndjson([+ { type: "RecurringPriceChange", data: {+ id: "old-change", recurring_transaction_id: "missing-series",+ effective_on: "2026-05-01", previous_amount: "10.0", new_amount: "12.0",+ currency: "USD" } }+ ])++ result = Family::DataImporter.new(@family, ndjson).import!++ assert_equal 1, result.dig(:summary, "recurring_price_changes", "skipped")+ end++ # A bill created with a full payment history must not also carry the+ # occurrences its own creation callback generates.+ test "imported occurrences do not duplicate the ones a new series generates" do+ Family::DataImporter.new(@family, build_ndjson(bills_ndjson_records)).import!++ series = @family.recurring_transactions.sole+ duplicates = series.recurring_occurrences.group(:original_due_on).count.select { |_, n| n > 1 }++ assert_empty duplicates, "generation and import collided on the same due date"+ end+++ # Occurrence generation fires after_commit on the instance the importer+ # created. If validation cached its rules while they were still empty, a+ # biweekly restore would materialize monthly phantom occurrences beside the+ # real schedule.+ test "a restored biweekly series keeps its cadence, with no monthly phantoms" do+ Family::DataImporter.new(@family, build_ndjson(bills_ndjson_records)).import!++ series = @family.recurring_transactions.find_by!(name: "Rent")++ # The imported historical row is weekend-adjusted off its weekday, so the+ # cadence check runs on what generation produced: every scheduled cycle+ # lands on the rule's weekday, fourteen days from its neighbour. A monthly+ # phantom would land on the 9th, whatever weekday that is.+ generated = series.recurring_occurrences.open_status.order(:due_on).pluck(:due_on)+ assert generated.any?, "generation must have materialized future cycles"++ generated.each do |due_on|+ assert_equal 1, due_on.cwday, "#{due_on} is not the rule's Monday"+ end+ generated.each_cons(2) do |a, b|+ assert_equal 14, (b - a).to_i, "#{a} to #{b} is not one biweekly step"+ end+ end++ # Session imports arrive in chunks, each processed by a fresh importer. The+ # occurrence map used to live in memory, so an allocation whose occurrence+ # landed in an earlier chunk was silently skipped.+ test "an allocation in a later session chunk finds its occurrence from an earlier one" do+ records = bills_ndjson_records+ allocations = records.select { |r| r[:type] == "RecurringAllocation" }+ rest = records - allocations+ assert allocations.any?, "fixture must carry at least one allocation"++ session = @family.import_sessions.create!(expected_chunks: 2)+ session.attach_chunk!(sequence: 1, client_chunk_id: "bills",+ content: build_ndjson(rest),+ filename: "bills.ndjson", content_type: "application/x-ndjson")+ session.attach_chunk!(sequence: 2, client_chunk_id: "allocations",+ content: build_ndjson(allocations),+ filename: "allocations.ndjson", content_type: "application/x-ndjson")++ session.publish++ series = @family.recurring_transactions.find_by!(name: "Rent")+ assert_operator RecurringAllocation.joins(:recurring_occurrence)+ .where(recurring_occurrences: { recurring_transaction_id: series.id }).count, :>, 0,+ "the later chunk's allocation must resolve its occurrence through the persisted mapping"+ end+privatedef build_ndjson(records)records.map(&:to_json).join("\n")end++ # A bill, one non-monthly rule, a settled occurrence, and the payment that+ # settled it, pointing at a transaction arriving in the same export.+ def bills_ndjson_records+ [+ { type: "Account", data: {+ id: "old-acct", name: "Checking", balance: "0", currency: "USD",+ accountable_type: "Depository", accountable: { subtype: "checking" } } },+ { type: "RecurringTransaction", data: {+ id: "old-series", account_id: "old-acct", amount: "2000.0", currency: "USD",+ expected_day_of_month: 9, last_occurrence_date: "2026-06-09",+ next_expected_date: "2026-07-09", status: "active", name: "Rent",+ manual: true, bill_type: "bill", amount_tolerance_pct: "9.5",+ anchor_date: "2026-06-09", weekend_adjust: "before", dedup_scope: "2000",+ matcher_hints: { "name_aliases" => [ "WATSON PROPERTY" ] } } },+ { type: "RecurrenceRule", data: {+ id: "old-rule", recurring_transaction_id: "old-series",+ frequency: "weekly", interval: 2, weekday: 1, position: 0 } },+ { type: "Transaction", data: {+ id: "old-txn", entry_id: "old-entry", account_id: "old-acct",+ date: "2026-06-09", amount: "2000.0", currency: "USD", name: "Rent payment" } },+ { type: "RecurringOccurrence", data: {+ id: "old-occ", recurring_transaction_id: "old-series",+ original_due_on: "2026-06-09", due_on: "2026-06-09", currency: "USD",+ expected_amount: "2000.0", status: "paid",+ closed_at: "2026-06-09T12:00:00Z", closed_source: "auto" } },+ { type: "RecurringAllocation", data: {+ id: "old-alloc", recurring_occurrence_id: "old-occ", transaction_id: "old-txn",+ allocated_amount: "2000.0", currency: "USD", state: "confirmed",+ source: "user_confirmed", paid_on: "2026-06-09" } }+ ]+ endenddiff --git a/test/models/insight/generators/cash_flow_warning_generator_test.rb b/test/models/insight/generators/cash_flow_warning_generator_test.rbnew file mode 100644index 0000000000..3dfb7228a3--- /dev/null+++ b/test/models/insight/generators/cash_flow_warning_generator_test.rb@@ -0,0 +1,44 @@+require "test_helper"++class Insight::Generators::CashFlowWarningGeneratorTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @series = @family.recurring_transactions.create!(+ name: "Horizon Power", account: accounts(:depository), amount: 100, currency: "USD",+ expected_day_of_month: 15, last_occurrence_date: Date.current,+ next_expected_date: 1.month.from_now.to_date, status: "active", manual: true+ )+ # The series generates its own horizon on create; clear it so the test+ # owns exactly three known occurrences.+ @series.recurring_occurrences.delete_all+ @occurrences = 3.times.map do |i|+ @series.recurring_occurrences.create!(+ family: @family,+ original_due_on: Date.current + i + 1,+ due_on: Date.current + i + 1,+ currency: "USD"+ )+ end+ RecurringAllocation.create!(+ recurring_occurrence: @occurrences.first, state: :confirmed, source: :user_confirmed,+ allocated_amount: 40, currency: "USD", paid_on: Date.current+ )+ end++ test "remaining amounts come from one grouped sum, not one query per occurrence" do+ generator = Insight::Generators::CashFlowWarningGenerator.new(@family)++ sum_queries = 0+ counter = ->(*, payload) do+ sum_queries += 1 if payload[:sql].to_s.match?(/SUM.*recurring_allocations/i)+ end++ entries = ActiveSupport::Notifications.subscribed(counter, "sql.active_record") do+ generator.send(:upcoming_recurring_entries)+ end++ assert_equal 1, sum_queries, "the confirmed-allocation sums must batch into one grouped query"+ assert_equal [ 60, 100, 100 ], entries.sort_by(&:date).map(&:amount).map(&:to_i),+ "the partially paid occurrence contributes only its remainder"+ end+enddiff --git a/test/models/insight/generators/subscription_audit_generator_test.rb b/test/models/insight/generators/subscription_audit_generator_test.rbindex 373b69e3ac..1c9a477e23 100644--- a/test/models/insight/generators/subscription_audit_generator_test.rb+++ b/test/models/insight/generators/subscription_audit_generator_test.rb@@ -4,16 +4,43 @@ class Insight::Generators::SubscriptionAuditGeneratorTest < ActiveSupport::TestCsetup do@family = families(:dylan_family)@overdue = recurring_transactions(:netflix_subscription)- @overdue.update!(next_expected_date: 50.days.ago.to_date)+ @overdue.recurring_occurrences.create!(+ family: @family,+ original_due_on: 50.days.ago.to_date,+ due_on: 50.days.ago.to_date,+ currency: @overdue.currency+ )end- test "generates an insight for an overdue recurring transaction" do+ test "generates an insight for an occurrence a full cycle overdue" doinsights = Insight::Generators::SubscriptionAuditGenerator.new(@family).generateassert_equal 1, insights.sizeassert_equal "subscription_audit:#{@overdue.id}", insights.first.dedup_keyend+ test "a quarterly bill between its normal occurrences is not nagged about" do+ @overdue.recurring_occurrences.delete_all+ quarterly = @family.recurring_transactions.create!(+ name: "Quarterly water", account: accounts(:depository), amount: 120, currency: "USD",+ expected_day_of_month: 15, anchor_date: 50.days.ago.to_date,+ last_occurrence_date: 50.days.ago.to_date, next_expected_date: 40.days.from_now.to_date,+ status: "active", manual: true+ )+ RecurringTransaction::FrequencyPreset.apply(quarterly, preset: "quarterly", day_of_month: "15")+ quarterly.save!+ quarterly.recurring_occurrences.delete_all+ # 50 days overdue is under one quarterly cycle: normal, not stale.+ quarterly.recurring_occurrences.create!(+ family: @family, original_due_on: 50.days.ago.to_date,+ due_on: 50.days.ago.to_date, currency: "USD"+ )++ insights = Insight::Generators::SubscriptionAuditGenerator.new(@family).generate++ assert_empty insights+ end+test "returns nothing when recurring transaction detection is disabled" do@family.update!(recurring_transactions_disabled: true)diff --git a/test/models/recurrence_rule_test.rb b/test/models/recurrence_rule_test.rbnew file mode 100644index 0000000000..10982485c5--- /dev/null+++ b/test/models/recurrence_rule_test.rb@@ -0,0 +1,122 @@+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+enddiff --git a/test/models/recurring_occurrence_test.rb b/test/models/recurring_occurrence_test.rbnew file mode 100644index 0000000000..56de786f66--- /dev/null+++ b/test/models/recurring_occurrence_test.rb@@ -0,0 +1,112 @@+require "test_helper"++class RecurringOccurrenceTest < ActiveSupport::TestCase+ def setup+ @family = families(:dylan_family)+ @series = recurring_transactions(:netflix_subscription)+ end++ test "expected amount inherits from the series until overridden" do+ occurrence = create_occurrence+ assert_equal @series.amount, occurrence.resolved_expected_amount++ # A series price edit reaches every open occurrence with zero sweeps.+ @series.update!(amount: 18.99)+ assert_equal 18.99, occurrence.resolved_expected_amount++ occurrence.override_amount!(20)+ assert_equal 20, occurrence.resolved_expected_amount++ occurrence.override_amount!(nil)+ assert_equal 18.99, occurrence.resolved_expected_amount+ end++ test "average strategy resolves through the series variance" do+ @series.update!(amount_strategy: "average", expected_amount_min: 10, expected_amount_max: 20, expected_amount_avg: 15.5)+ occurrence = create_occurrence+ assert_equal 15.5, occurrence.resolved_expected_amount+ end++ test "closing freezes the resolved amount so later series edits cannot rewrite history" do+ occurrence = create_occurrence+ occurrence.skip!++ @series.update!(amount: 99.99)+ assert_equal 15.99, occurrence.reload.expected_amount+ assert_equal 15.99, occurrence.resolved_expected_amount+ end++ test "reopening keeps the frozen amount as an explicit override" do+ occurrence = create_occurrence+ occurrence.close!("paid", source: "user")+ occurrence.reopen!++ assert occurrence.scheduled?+ assert_nil occurrence.closed_at+ assert_equal 15.99, occurrence.expected_amount+ end++ test "derived state walks upcoming, due, overdue with snooze respected" do+ travel_to Date.new(2026, 8, 13) do+ assert_equal :upcoming, create_occurrence(due_on: Date.new(2026, 8, 20), original: Date.new(2026, 8, 20)).derived_state+ assert_equal :due, create_occurrence(due_on: Date.new(2026, 8, 15), original: Date.new(2026, 8, 15)).derived_state+ assert_equal :due, create_occurrence(due_on: Date.new(2026, 8, 11), original: Date.new(2026, 8, 11)).derived_state++ overdue = create_occurrence(due_on: Date.new(2026, 8, 5), original: Date.new(2026, 8, 5))+ assert_equal :overdue, overdue.derived_state++ overdue.snooze!(Date.new(2026, 8, 25))+ assert_equal :upcoming, overdue.derived_state+ end+ end++ test "partial payment is exact-sum, never tolerance" do+ occurrence = create_occurrence+ occurrence.allocations.create!(allocated_amount: 10, currency: "USD", source: "user_created")++ assert occurrence.partially_paid?+ assert_equal 5.99, occurrence.remaining_amount+ end++ test "last strategy resolves to what the previous cycle actually cost" do+ @series.update!(amount_strategy: "last")++ # Expected 15.99, really charged 17.25: inside tolerance, so it closes as+ # actual-replaces-estimate and the frozen expected stays at the estimate.+ settled = create_occurrence(due_on: Date.current - 30, original: Date.current - 30)+ settled.allocations.create!(allocated_amount: 17.25, currency: "USD",+ state: "confirmed", source: "user_created")+ settled.close!("paid", source: "auto")++ assert_equal 15.99, settled.reload.expected_amount, "the frozen value is the estimate"+ assert_equal 17.25, create_occurrence.resolved_expected_amount,+ "'last' must propose the real charge, not the old estimate"+ end++ test "last strategy ignores a paid cycle that carries no payments" do+ @series.update!(amount_strategy: "last")+ create_occurrence(due_on: Date.current - 30, original: Date.current - 30)+ .close!("paid", source: "user")++ assert_equal 15.99, create_occurrence.resolved_expected_amount+ end++ test "the system never sets missed" do+ occurrence = create_occurrence(due_on: 3.months.ago.to_date, original: 3.months.ago.to_date)+ assert_equal :overdue, occurrence.derived_state++ occurrence.miss!+ assert occurrence.missed?+ assert_equal "user", occurrence.closed_source+ end++ private+ def create_occurrence(due_on: Date.current + 10, original: nil)+ @series.recurring_occurrences.create!(+ family: @family,+ original_due_on: original || due_on,+ due_on: due_on,+ currency: "USD"+ )+ end+enddiff --git a/test/models/recurring_transaction/allocator_concurrency_test.rb b/test/models/recurring_transaction/allocator_concurrency_test.rbnew file mode 100644index 0000000000..152d1d3b5a--- /dev/null+++ b/test/models/recurring_transaction/allocator_concurrency_test.rb@@ -0,0 +1,134 @@+require "test_helper"+require "concurrent"++# One transaction must never be allocated beyond its own amount, no matter how+# many occurrences want it at once. The occurrence row lock cannot enforce this+# on its own: allocations against two DIFFERENT occurrences take two different+# row locks and never meet, so both read the same stale capacity.+#+# Real threads on real connections, so this needs real commits.+class RecurringTransaction::AllocatorConcurrencyTest < ActiveSupport::TestCase+ self.use_transactional_tests = false++ setup do+ @family = Family.create!(name: "Allocator Race", currency: "USD")+ @account = Account.create!(+ family: @family, name: "Checking", currency: "USD",+ balance: 0, accountable: Depository.new)++ @entry = Entry.create!(+ account: @account, name: "One payment", date: Date.current,+ amount: 1000, currency: "USD", entryable: Transaction.new)++ @first = occurrence_for("Rent")+ @second = occurrence_for("Storage")+ end++ teardown do+ RecurringAllocation.where(entry_id: @entry.id).delete_all+ RecurringOccurrence.where(family_id: @family.id).delete_all+ RecurringTransaction.where(family_id: @family.id).delete_all+ Entry.where(account_id: @account.id).delete_all+ @account.destroy+ @family.destroy+ end++ test "one entry cannot be allocated past its amount by concurrent writers" do+ latch = Concurrent::CountDownLatch.new(2)++ outcomes = [ @first, @second ].map do |occurrence|+ Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do+ # Both threads reach the capacity read before either inserts, which+ # is the interleaving the row lock cannot prevent.+ latch.count_down+ latch.wait(5)+ RecurringTransaction::Allocator.new(occurrence).allocate!(entry: @entry, amount: 600)+ :allocated+ rescue RecurringTransaction::Allocator::OverAllocationError+ :rejected+ end+ end+ end.map(&:value)++ allocated = RecurringAllocation.where(entry_id: @entry.id).sum(:allocated_amount)++ assert_equal 600, allocated,+ "two 600 allocations of a 1000 transaction must not both survive (got #{allocated})"+ assert_includes outcomes, :rejected, "the second writer should have been rejected"+ end++ # The two sides use different write paths, so the guard has to sit on the+ # entry rather than on either path.+ test "a manual attach and the matcher cannot both spend the same transaction" do+ latch = Concurrent::CountDownLatch.new(2)++ [+ Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do+ latch.count_down+ latch.wait(5)+ RecurringTransaction::Allocator.new(@first).allocate!(entry: @entry, amount: 700)+ rescue RecurringTransaction::Allocator::OverAllocationError+ nil+ end+ end,+ Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do+ latch.count_down+ latch.wait(5)+ RecurringTransaction::Allocator.new(@second).allocate_matched!(+ entry: @entry, state: "confirmed", confidence: 0.9, signals: {})+ rescue RecurringTransaction::Allocator::OverAllocationError+ nil+ end+ end+ ].each(&:join)++ allocated = RecurringAllocation.where(entry_id: @entry.id)+ .sum("COALESCE(source_amount, allocated_amount)")++ assert_operator allocated, :<=, @entry.amount.abs,+ "a 1000 transaction cannot fund more than 1000 of bills"+ end++ # Deleting a transaction must not take the payment record with it, and must+ # never leave an allocation pointing at a row that is gone.+ test "deleting a linked transaction leaves the payment intact and unlinked" do+ RecurringTransaction::Allocator.new(@first).allocate!(entry: @entry, amount: 400)+ allocation = RecurringAllocation.find_by!(entry_id: @entry.id)++ @entry.destroy++ allocation.reload+ assert_nil allocation.entry_id+ assert_equal 400, allocation.allocated_amount.to_f+ end++ test "an exhausted entry allocates nothing rather than the occurrence balance" do+ RecurringTransaction::Allocator.new(@first).allocate!(entry: @entry, amount: 1000)++ assert_nil RecurringTransaction::Allocator.new(@second).allocate_matched!(+ entry: @entry, state: "confirmed", confidence: 0.9, signals: {})++ assert_equal 1000, RecurringAllocation.where(entry_id: @entry.id).sum(:allocated_amount)+ end++ private+ def occurrence_for(name)+ series = RecurringTransaction.create!(+ family: @family, account: @account, name: name, amount: 800,+ currency: "USD", expected_day_of_month: 9, status: "active",+ manual: true, bill_type: "bill",+ last_occurrence_date: Date.current, next_expected_date: Date.current)++ due = Date.current.beginning_of_month + 7+ RecurringOccurrence.find_or_create_by!(+ recurring_transaction: series, family: @family, original_due_on: due) do |row|+ row.due_on = due+ row.currency = "USD"+ row.expected_amount = 800+ row.status = "scheduled"+ end+ end+enddiff --git a/test/models/recurring_transaction/allocator_test.rb b/test/models/recurring_transaction/allocator_test.rbnew file mode 100644index 0000000000..f2804aae5f--- /dev/null+++ b/test/models/recurring_transaction/allocator_test.rb@@ -0,0 +1,331 @@+require "test_helper"++class RecurringTransaction::AllocatorTest < ActiveSupport::TestCase+ Allocator = RecurringTransaction::Allocator++ def setup+ @family = families(:dylan_family)+ @account = accounts(:depository)+ @rent = @family.recurring_transactions.create!(+ account: @account,+ name: "Watson Property",+ amount: 2000,+ currency: "USD",+ expected_day_of_month: 29,+ last_occurrence_date: Date.current,+ next_expected_date: 1.month.from_now.to_date,+ status: "active",+ manual: true+ )+ @occurrence = @rent.recurring_occurrences.order(:due_on).last ||+ @rent.recurring_occurrences.create!(family: @family,+ original_due_on: (Date.current + 1.month).beginning_of_month + 9,+ due_on: (Date.current + 1.month).beginning_of_month + 9,+ currency: "USD")+ @allocator = Allocator.new(@occurrence)+ end++ test "a currency mismatch reads as a sentence, not a missing translation" do+ allocation = RecurringAllocation.new(+ recurring_occurrence: @occurrence, state: :confirmed, source: :user_confirmed,+ allocated_amount: 10, currency: "EUR", paid_on: Date.current+ )++ assert_not allocation.valid?+ message = allocation.errors.full_messages_for(:currency).join+ assert_no_match(/translation missing/i, message)+ end++ test "a price rise does not re-target an occurrence that has already been paid against" do+ @occurrence.update!(expected_amount: nil) # inheriting from the series+ @allocator.allocate!(entry: entry_for(500))++ assert_equal 1500, @occurrence.reload.remaining_amount++ @rent.update!(amount: 2500)++ occurrence = @occurrence.reload+ assert_equal 2000, occurrence.resolved_expected_amount,+ "the $500 was paid against a $2,000 obligation and must stay against it"+ assert_equal 1500, occurrence.remaining_amount+ end++ test "a price rise still updates an open occurrence nobody has paid against" do+ @occurrence.update!(expected_amount: nil)++ @rent.update!(amount: 2500)++ assert_equal 2500, @occurrence.reload.resolved_expected_amount+ end++ test "a suggestion does not pin the amount" do+ @occurrence.update!(expected_amount: nil)+ @allocator.allocate_matched!(entry: entry_for(500), state: "suggested", confidence: 0.7, signals: {})++ @rent.update!(amount: 2500)++ assert_nil @occurrence.reload.expected_amount+ assert_equal 2500, @occurrence.resolved_expected_amount+ end++ test "a partial payment teaches the matcher nothing about tolerance" do+ # $1,625 against $2,000 rent is an installment, not evidence rent varies.+ # It is the only allocation, which is what used to be mistaken for proof.+ @allocator.allocate!(entry: entry_for(1625))++ assert @occurrence.reload.partially_paid?+ assert_nil @rent.reload.matcher_hints["learned_tolerance_pct"]+ end++ test "a single payment that settles the bill above the band does widen tolerance" do+ # $2,200 settles a $2,000 obligation and sits outside the 7.5% band, so the+ # band really was too tight.+ @allocator.allocate!(entry: entry_for(2200))++ assert @occurrence.reload.paid?+ assert_equal 10.0, @rent.reload.matcher_hints["learned_tolerance_pct"]+ end++ test "partial payments accumulate and close only at the exact sum" do+ @allocator.allocate!(entry: entry_for(750))+ @allocator.allocate!(entry: entry_for(500))++ assert @occurrence.reload.partially_paid?+ assert_equal 750, @occurrence.remaining_amount++ @allocator.allocate!(entry: entry_for(750))++ assert @occurrence.reload.paid?+ assert_equal "auto", @occurrence.closed_source+ end++ test "1850 of 2000 stays partially paid, never paid" do+ # The Check Mode regression: tolerance-close must not apply to+ # accumulated partials.+ @allocator.allocate!(entry: entry_for(750))+ @allocator.allocate!(entry: entry_for(500))+ @allocator.allocate!(entry: entry_for(600))++ occurrence = @occurrence.reload+ assert occurrence.scheduled?, "must NOT close"+ assert occurrence.partially_paid?+ assert_equal 150, occurrence.remaining_amount+ end++ test "a single payment within tolerance closes as actual-replaces-estimate" do+ # Expected $2,000 ± 7.5%; one charge of $2,080 IS the bill.+ @allocator.allocate!(entry: entry_for(2080))++ occurrence = @occurrence.reload+ assert occurrence.paid?+ assert_equal "auto", occurrence.closed_source+ end++ test "a single payment below the band stays partial" do+ @allocator.allocate!(entry: entry_for(1500))+ assert @occurrence.reload.partially_paid?+ end++ test "overpayment closes and flags" do+ # The default allocation takes only what the occurrence needs, so an+ # overpay has to be explicit.+ @allocator.allocate!(entry: entry_for(1200), amount: 1200)+ @allocator.allocate!(entry: entry_for(1200), amount: 1200)++ occurrence = @occurrence.reload+ assert occurrence.paid?+ assert occurrence.overpaid?+ end++ test "removing the satisfying allocation reopens an auto-closed occurrence but never a user-closed one" do+ allocation = @allocator.allocate!(entry: entry_for(2000))+ assert @occurrence.reload.paid?++ @allocator.unallocate!(allocation)+ assert @occurrence.reload.scheduled?, "auto-closed reopens"++ @allocator.mark_paid!+ assert @occurrence.reload.paid?+ assert_equal "user", @occurrence.closed_source++ padding = @occurrence.allocations.order(:created_at).last+ @allocator.unallocate!(padding)+ assert @occurrence.reload.paid?, "user-closed never auto-reopens"+ end++ test "mark_paid! settles the remainder without a transaction" do+ @allocator.allocate!(entry: entry_for(537.50))+ @allocator.mark_paid!++ occurrence = @occurrence.reload+ assert occurrence.paid?+ manual = occurrence.allocations.where(entry_id: nil).first+ assert_equal 1462.50, manual.allocated_amount+ assert manual.from_user_created?+ end++ test "one entry can pay several occurrences but never more than itself" do+ lump = entry_for(1612.50)+ # A mid-month date the day-29 series never generates, so this manual+ # row can never collide with the generator's rows regardless of what+ # Date.current is when the suite runs.+ free_date = (Date.current + 2.months).beginning_of_month + 9+ september = @rent.recurring_occurrences.create!(+ family: @family, original_due_on: free_date, due_on: free_date, currency: "USD"+ )++ @allocator.allocate!(entry: lump, amount: 1000)+ Allocator.new(september).allocate!(entry: lump, amount: 612.50)++ assert_raises Allocator::OverAllocationError do+ Allocator.new(september).allocate!(entry: lump, amount: 500)+ end+ end++ test "the same entry cannot be allocated twice to one occurrence" do+ # Partial amounts so the capacity guard passes; the unique index is the+ # backstop this test pins.+ payment = entry_for(500)+ @allocator.allocate!(entry: payment, amount: 200)++ assert_raises ActiveRecord::RecordNotUnique do+ @allocator.allocate!(entry: payment, amount: 100)+ end+ end++ test "default allocation takes what the occurrence needs, not the whole entry" do+ @allocator.allocate!(entry: entry_for(1900))+ big = entry_for(500)+ allocation = @allocator.allocate!(entry: big)++ assert_equal 100, allocation.allocated_amount+ assert @occurrence.reload.paid?+ end++ test "a cross-currency entry without a rate demands an explicit amount" do+ foreign = @account.entries.create!(+ date: Date.current, amount: 100, currency: "EUR", name: "EU charge",+ entryable: Transaction.new+ )++ assert_raises Allocator::MissingRateError do+ @allocator.allocate!(entry: foreign)+ end++ allocation = @allocator.allocate!(entry: foreign, amount: 110)+ assert_equal 110, allocation.allocated_amount+ assert_equal "USD", allocation.currency+ assert_equal "EUR", allocation.source_currency+ end++ test "a partly allocated cross-currency entry defaults to its leftover" do+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", rate: 1.1, date: Date.current)+ foreign = @account.entries.create!(+ date: Date.current, amount: 100, currency: "EUR", name: "EU charge",+ entryable: Transaction.new+ )+ @allocator.allocate!(entry: foreign, amount: 55)++ free_date = (Date.current + 2.months).beginning_of_month + 9+ other = @rent.recurring_occurrences.create!(+ family: @family, original_due_on: free_date, due_on: free_date, currency: "USD"+ )+ # 50 EUR of the entry is spoken for, so the default is the 50 EUR+ # leftover converted, not the full 100 the old default reached for.+ allocation = Allocator.new(other).allocate!(entry: foreign)++ assert_equal 55, allocation.allocated_amount+ assert_equal 50, allocation.source_amount+ end++ test "a cross-currency default takes what the occurrence needs, not the whole entry" do+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", rate: 1.1, date: Date.current)+ @allocator.allocate!(entry: entry_for(1900))+ foreign = @account.entries.create!(+ date: Date.current, amount: 200, currency: "EUR", name: "EU charge",+ entryable: Transaction.new+ )+ allocation = @allocator.allocate!(entry: foreign)++ assert_equal 100, allocation.allocated_amount+ assert @occurrence.reload.paid?+ end++ test "entry deletion nullifies the link but keeps the payment" do+ payment = entry_for(500)+ allocation = @allocator.allocate!(entry: payment)++ payment.destroy!++ allocation.reload+ assert_nil allocation.entry_id+ assert_equal 500, allocation.allocated_amount+ end+++ # Without a rate for the entry's date an allocation has no source amount, so+ # it cannot be measured against the transaction. The guard used to skip those+ # entirely, and entry_capacity summed COALESCE(source_amount, allocated_amount)+ # across currencies, so one 100 EUR transaction could pay 150 USD twice and+ # keep going.+ test "an unmeasurable entry cannot be spread across several occurrences" do+ ExchangeRate.delete_all+ entry = foreign_entry(amount: 100, currency: "EUR")+ first_occurrence = usd_occurrence(expected: 150)+ second_occurrence = usd_occurrence(expected: 150, due_on: Date.current + 30)++ RecurringTransaction::Allocator.new(first_occurrence).allocate!(amount: 150, entry: entry)++ assert_raises RecurringTransaction::Allocator::OverAllocationError do+ RecurringTransaction::Allocator.new(second_occurrence).allocate!(amount: 150, entry: entry)+ end++ assert_equal 1, RecurringAllocation.where(entry: entry).count,+ "one judgement call is allowed; an unbounded fan-out is not"+ end++ test "the first unmeasurable allocation is still permitted" do+ ExchangeRate.delete_all+ entry = foreign_entry(amount: 100, currency: "EUR")+ occurrence = usd_occurrence(expected: 150)++ allocation = RecurringTransaction::Allocator.new(occurrence).allocate!(amount: 150, entry: entry)++ assert allocation.persisted?+ assert_nil allocation.source_amount+ end++ private++ def foreign_entry(amount:, currency:)+ account = accounts(:depository)+ account.entries.create!(+ name: "Foreign charge", date: Date.current, amount: amount,+ currency: currency, entryable: Transaction.new+ )+ end++ def usd_occurrence(expected:, due_on: Date.current)+ series = @family.recurring_transactions.create!(+ name: "Bill #{expected} #{due_on}", account: accounts(:depository),+ amount: expected, currency: "USD", status: "active", bill_type: "bill",+ manual: true, dedup_scope: "bill-#{expected}-#{due_on}",+ expected_day_of_month: due_on.day, last_occurrence_date: 1.month.ago.to_date,+ next_expected_date: due_on+ )+ series.recurring_occurrences.destroy_all+ series.recurring_occurrences.create!(+ family: @family, original_due_on: due_on, due_on: due_on,+ currency: "USD", expected_amount: expected, status: "scheduled"+ )+ end+ def entry_for(amount)+ @account.entries.create!(+ date: Date.current,+ amount: amount,+ currency: "USD",+ name: "Watson Property",+ entryable: Transaction.new+ )+ end+enddiff --git a/test/models/recurring_transaction/classifier_test.rb b/test/models/recurring_transaction/classifier_test.rbnew file mode 100644index 0000000000..970ebe8253--- /dev/null+++ b/test/models/recurring_transaction/classifier_test.rb@@ -0,0 +1,124 @@+require "test_helper"++class RecurringTransaction::ClassifierTest < ActiveSupport::TestCase+ Classifier = RecurringTransaction::Classifier++ def setup+ @family = families(:dylan_family)+ @depository = accounts(:depository)+ @credit_card = accounts(:credit_card)+ end++ test "known services classify as subscriptions with autopay on" do+ result = Classifier.classify(name: "Netflix.com", entries: entries_of(15.99, 15.99), account: @depository)++ assert_equal "subscription", result.bill_type+ assert result.autopay+ end++ test "utility and telecom wording classifies as a bill even when flat" do+ result = Classifier.classify(name: "XFINITY INTERNET", entries: entries_of(89.99, 89.99), account: @credit_card)++ assert_equal "bill", result.bill_type+ assert_not result.autopay+ end++ test "ach and billpay descriptors are push payments, not subscriptions" do+ result = Classifier.classify(name: "WATSON PROPERTY WEB PMT", entries: entries_of(537.50, 537.50), account: @depository)++ assert_equal "bill", result.bill_type+ end++ test "a flat modest card charge with no name signal reads as a subscription" do+ result = Classifier.classify(name: "SOMEOBSCURESERVICE", entries: entries_of(9.99, 9.99), account: @credit_card)++ assert_equal "subscription", result.bill_type+ end++ test "varying amounts break the card-charge heuristic" do+ result = Classifier.classify(name: "SOMEOBSCURESERVICE", entries: entries_of(42.17, 39.80), account: @credit_card)++ assert_equal "bill", result.bill_type+ end++ test "interest charges never read as subscriptions someone chose" do+ result = Classifier.classify(name: "Interest Charge", entries: entries_of(2.14, 2.14), account: @credit_card)++ assert_equal "bill", result.bill_type+ end++ test "the series inherits the cluster's most common category" do+ food = categories(:food_and_drink)+ tagged = entries_of(12, 12, 12)+ tagged.first(2).each { |entry| entry.entryable.update!(category: food) }++ result = Classifier.classify(name: "MYSTERY BOX", entries: tagged, account: @depository)++ assert_equal food.id, result.category_id+ end++ test "detection creates classified suggestions" do+ @family.recurring_transactions.destroy_all+ [ 0, 1, 2 ].each do |months_ago|+ @credit_card.entries.create!(+ date: months_ago.months.ago.beginning_of_month + 7.days,+ amount: 15.99, currency: "USD", name: "SPOTIFY USA",+ entryable: Transaction.new+ )+ end++ RecurringTransaction::Identifier.new(@family).identify_recurring_patterns++ created = @family.recurring_transactions.find_by(name: "SPOTIFY USA")+ assert_equal "subscription", created.bill_type+ assert created.autopay+ assert_equal "suggested", created.status+ end+++ # A substring test let "max" claim any Maxwell and "gas" claim a gastropub,+ # and a false subscription match also set autopay, which hides the row from+ # the needs-action list.+ test "short keywords only match whole words" do+ result = RecurringTransaction::Classifier.classify(+ name: "Maxwell Plumbing", entries: entries_of(45)+ )+ assert_equal "bill", result.bill_type, "Maxwell is not HBO Max"+ end++ test "the real service names still match" do+ result = RecurringTransaction::Classifier.classify(+ name: "HBO MAX SUBSCRIPTION", entries: entries_of(15.99)+ )+ assert_equal "subscription", result.bill_type+ end++ # The word-boundary fix silently disabled the stems: utilit never+ # matches UTILITIES. Starred stems accept a suffix without regaining the+ # anywhere-in-the-word looseness the boundary fix removed.+ test "keyword stems still reach their inflections" do+ utilities = RecurringTransaction::Classifier.classify(+ name: "AUSTIN UTILITIES", entries: entries_of(120)+ )+ assert_equal "bill", utilities.bill_type+ assert_not utilities.autopay, "a utility is not autopay by default"++ insurer = RecurringTransaction::Classifier.classify(+ name: "STATE FARM INSUR PREM", entries: entries_of(140)+ )+ assert_equal "bill", insurer.bill_type+ end++ private+ def entries_of(*amounts)+ amounts.map.with_index do |amount, index|+ @depository.entries.create!(+ date: index.months.ago.to_date,+ amount: amount,+ currency: "USD",+ name: "classifier test entry #{index}",+ entryable: Transaction.new+ )+ end+ end+enddiff --git a/test/models/recurring_transaction/declared_bill_test.rb b/test/models/recurring_transaction/declared_bill_test.rbnew file mode 100644index 0000000000..24882465d9--- /dev/null+++ b/test/models/recurring_transaction/declared_bill_test.rb@@ -0,0 +1,70 @@+require "test_helper"++class RecurringTransaction::DeclaredBillTest < ActiveSupport::TestCase+ setup do+ @user = users(:family_admin)+ @family = @user.family+ end++ test "an unparseable amount becomes a validation error, not an exception" do+ series = build_bill(amount: "$40.00")++ assert_not series.errors.none?+ assert_includes series.errors.full_messages.to_sentence,+ I18n.t("recurring_transactions.create.amount_invalid")+ end++ test "a plain numeric amount still builds" do+ series = build_bill(amount: "40.00")++ assert series.errors.none?+ assert_equal 40, series.amount+ end++ test "a non-finite amount becomes a validation error, not a saved bill" do+ %w[Infinity -Infinity NaN].each do |value|+ series = build_bill(amount: value)++ assert_not series.errors.none?, "#{value} must not build a valid bill"+ assert_includes series.errors.full_messages.to_sentence,+ I18n.t("recurring_transactions.create.amount_invalid")+ end+ end++ test "the same identity at the same amount reports a duplicate instead of raising" do+ # The amount is stamped into dedup_scope before the first insert, so the+ # very first identical duplicate collides and must surface as a validation+ # error rather than an escaping RecordNotUnique.+ assert RecurringTransaction::DeclaredBill.save(build_bill(amount: "40"))++ duplicate = build_bill(amount: "40")+ assert_not RecurringTransaction::DeclaredBill.save(duplicate)+ assert_includes duplicate.errors.full_messages.to_sentence,+ I18n.t("recurring_transactions.create.already_exists")+ assert_equal 1, @family.recurring_transactions.where(name: "Trash Pickup").count+ end++ test "the same identity at a different amount forks on the amount" do+ first = build_bill(amount: "40")+ assert RecurringTransaction::DeclaredBill.save(first)++ other_tier = build_bill(amount: "65")+ assert RecurringTransaction::DeclaredBill.save(other_tier),+ "a second tier from the same biller is a legitimate second series"+ end++ private+ def build_bill(amount:)+ RecurringTransaction::DeclaredBill.new(+ family: @family,+ user: @user,+ attrs: {+ name: "Trash Pickup",+ amount: amount,+ account_id: accounts(:depository).id,+ first_due_on: (Date.current + 10).iso8601,+ frequency_preset: "monthly"+ }+ ).build+ end+enddiff --git a/test/models/recurring_transaction/frequency_preset_test.rb b/test/models/recurring_transaction/frequency_preset_test.rbnew file mode 100644index 0000000000..04a0c7d84b--- /dev/null+++ b/test/models/recurring_transaction/frequency_preset_test.rb@@ -0,0 +1,143 @@+require "test_helper"++class RecurringTransaction::FrequencyPresetTest < ActiveSupport::TestCase+ Preset = RecurringTransaction::FrequencyPreset++ def setup+ @recurring = recurring_transactions(:netflix_subscription)+ end++ test "detect reads zero rules as legacy monthly on the expected day" do+ found = Preset.detect(@recurring)+ assert_equal "monthly", found.key+ assert_equal @recurring.expected_day_of_month, found.day_of_month+ end++ test "apply weekly replaces the rules and syncs the non-authoritative day" do+ @recurring.update!(anchor_date: Date.new(2026, 8, 7))+ Preset.apply(@recurring, preset: "weekly", weekday: "5")+ @recurring.save!++ rules = @recurring.recurrence_rules.reload+ assert_equal 1, rules.size+ assert_equal "weekly", rules.first.frequency+ assert_equal 5, rules.first.weekday+ assert_equal 7, @recurring.expected_day_of_month, "weekly bills carry the anchor's day, not the old monthly day"++ assert_equal "weekly", Preset.detect(@recurring.reload).key+ end++ test "apply biweekly ensures an anchor and an interval of 2" do+ @recurring.update!(anchor_date: nil)+ Preset.apply(@recurring, preset: "biweekly", weekday: "5")+ @recurring.save!++ rule = @recurring.recurrence_rules.reload.first+ assert_equal 2, rule.interval+ assert_equal @recurring.last_occurrence_date, @recurring.anchor_date+ assert_equal "biweekly", Preset.detect(@recurring).key+ end++ test "apply semimonthly builds two sorted monthly rules" do+ Preset.apply(@recurring, preset: "semimonthly", day_of_month: "20", second_day_of_month: "5")+ @recurring.save!++ days = @recurring.recurrence_rules.reload.map(&:day_of_month)+ assert_equal [ 5, 20 ], days+ assert_equal 5, @recurring.expected_day_of_month++ found = Preset.detect(@recurring)+ assert_equal "semimonthly", found.key+ assert_equal 5, found.day_of_month+ assert_equal 20, found.second_day_of_month+ end++ test "apply annual defaults month and day from the anchor" do+ @recurring.update!(anchor_date: Date.new(2026, 3, 14))+ Preset.apply(@recurring, preset: "annual")+ @recurring.save!++ rule = @recurring.recurrence_rules.reload.first+ assert_equal "yearly", rule.frequency+ assert_equal 3, rule.month_of_year+ assert_equal 14, rule.day_of_month+ end++ test "apply is a no-op when the submitted cadence matches the current one" do+ Preset.apply(@recurring, preset: "quarterly", day_of_month: "10")+ @recurring.save!+ rule_ids = @recurring.recurrence_rules.reload.map(&:id)++ Preset.apply(@recurring, preset: "quarterly", day_of_month: "10")+ @recurring.save!++ assert_equal rule_ids, @recurring.recurrence_rules.reload.map(&:id)+ end++ test "apply with last day sets expected_day_of_month to 31" do+ Preset.apply(@recurring, preset: "monthly", day_of_month: RecurrenceRule::LAST.to_s)+ @recurring.save!++ assert_equal RecurrenceRule::LAST, @recurring.recurrence_rules.reload.first.day_of_month+ assert_equal 31, @recurring.expected_day_of_month+ end++ test "apply ignores unknown presets and custom" do+ Preset.apply(@recurring, preset: "custom")+ Preset.apply(@recurring, preset: "hourly")+ assert_empty @recurring.recurrence_rules+ end++ test "shapes the picker cannot express detect as custom" do+ @recurring.recurrence_rules.create!(frequency: "monthly", weekday: 5, weekday_ordinal: 3)+ assert_equal "custom", Preset.detect(@recurring.reload).key+ end++ test "labels read naturally" do+ assert_equal "Monthly on the 5th", Preset.label(@recurring)++ Preset.apply(@recurring, preset: "biweekly", weekday: "5")+ @recurring.save!+ assert_equal "Every 2 weeks on Friday", Preset.label(@recurring.reload)++ Preset.apply(@recurring, preset: "monthly", day_of_month: RecurrenceRule::LAST.to_s)+ @recurring.save!+ assert_equal "Monthly on the last day", Preset.label(@recurring.reload)+ end++ test "monthly equivalent amount normalizes cadence" do+ assert_in_delta @recurring.amount, @recurring.monthly_equivalent_amount.amount.to_f, 0.01++ Preset.apply(@recurring, preset: "annual")+ @recurring.save!+ assert_in_delta @recurring.amount / 12.0, @recurring.reload.monthly_equivalent_amount.amount.to_f, 0.01+ end++ # (15, LAST) and (LAST, 15) are one schedule. Without a canonical order each+ # reapply rewrote the rules instead of no-opping, and two equal anchors made+ # two identical monthly rules read back as semimonthly.+ test "semimonthly with a last-day anchor round-trips as a no-op" do+ Preset.apply(@recurring, preset: "semimonthly",+ day_of_month: 15, second_day_of_month: RecurrenceRule::LAST)+ @recurring.save!+ first_shape = @recurring.recurrence_rules.reload.map { |r| [ r.frequency, r.day_of_month ] }.sort_by(&:to_s)++ found = Preset.detect(@recurring)+ assert_equal "semimonthly", found.key++ Preset.apply(@recurring, preset: "semimonthly",+ day_of_month: found.day_of_month, second_day_of_month: found.second_day_of_month)+ @recurring.save!++ assert_equal first_shape,+ @recurring.recurrence_rules.reload.map { |r| [ r.frequency, r.day_of_month ] }.sort_by(&:to_s),+ "reapplying what detect reported must change nothing"+ end++ test "two equal anchors are one monthly schedule" do+ Preset.apply(@recurring, preset: "semimonthly", day_of_month: 5, second_day_of_month: 5)+ @recurring.save!++ assert_equal "monthly", Preset.detect(@recurring.reload).key+ end+enddiff --git a/test/models/recurring_transaction/history_backfiller_test.rb b/test/models/recurring_transaction/history_backfiller_test.rbnew file mode 100644index 0000000000..1fc45f9c5b--- /dev/null+++ b/test/models/recurring_transaction/history_backfiller_test.rb@@ -0,0 +1,113 @@+require "test_helper"++class RecurringTransaction::HistoryBackfillerTest < ActiveSupport::TestCase+ Backfiller = RecurringTransaction::HistoryBackfiller++ def setup+ @family = families(:dylan_family)+ @account = accounts(:depository)+ @family.recurring_transactions.destroy_all+ end++ test "closes history a real entry anchors and prunes the rest" do+ travel_to Date.new(2026, 8, 10) do+ series = create_series(name: "CITY WATER", amount: 80, day_offset: -1)+ # A four-month window (from Apr 10) materializes May/Jun/Jul; entries+ # cover two of them and May is a gap.+ create_entry(amount: 80, date: Date.new(2026, 7, 9), name: "CITY WATER")+ create_entry(amount: 80, date: Date.new(2026, 6, 9), name: "CITY WATER")++ pruned = Backfiller.new(@family, months: 4).run!++ paid = series.recurring_occurrences.paid.pluck(:due_on)+ assert_includes paid, Date.new(2026, 7, 9)+ assert_includes paid, Date.new(2026, 6, 9)+ assert_not_includes series.recurring_occurrences.pluck(:due_on), Date.new(2026, 5, 9),+ "an uncovered past occurrence is deleted, not kept as debt"+ assert_operator pruned, :>=, 1+ end+ end++ test "running twice is byte-identical" do+ travel_to Date.new(2026, 8, 10) do+ series = create_series(name: "CITY WATER", amount: 80, day_offset: -1)+ create_entry(amount: 80, date: Date.new(2026, 7, 9), name: "CITY WATER")++ Backfiller.new(@family, months: 3).run!+ state = snapshot(series)++ Backfiller.new(@family, months: 3).run!+ assert_equal state, snapshot(series)+ end+ end++ test "pre-existing allocations are never touched" do+ travel_to Date.new(2026, 8, 10) do+ series = create_series(name: "CITY WATER", amount: 80, day_offset: -1)+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.new(2026, 6, 1))+ past = series.recurring_occurrences.find_by!(due_on: Date.new(2026, 7, 9))+ allocation = past.allocations.create!(allocated_amount: 80, currency: "USD", source: "user_created")++ Backfiller.new(@family, months: 3).run!++ assert RecurringAllocation.exists?(allocation.id)+ assert RecurringOccurrence.exists?(past.id), "an allocated row survives the prune"+ end+ end++ test "series_scope narrows generation and pruning to the given series" do+ travel_to Date.new(2026, 8, 10) do+ target = create_series(name: "CITY WATER", amount: 80, day_offset: -1)+ other = create_series(name: "CITY GAS", amount: 55, day_offset: -1)+ create_entry(amount: 80, date: Date.new(2026, 7, 9), name: "CITY WATER")++ Backfiller.new(+ @family,+ months: 3,+ series_scope: @family.recurring_transactions.where(id: target.id)+ ).run!++ assert_operator target.recurring_occurrences.where("due_on < ?", Date.new(2026, 8, 1)).count, :>=, 1+ assert_equal 0, other.recurring_occurrences.where("due_on < ?", Date.new(2026, 8, 1)).count,+ "an unscoped series gains no backfilled history"+ end+ end++ private++ def snapshot(series)+ [+ series.recurring_occurrences.order(:due_on).pluck(:due_on, :status),+ RecurringAllocation.joins(:recurring_occurrence)+ .where(recurring_occurrences: { recurring_transaction_id: series.id })+ .count+ ]+ end++ def create_series(amount:, day_offset:, name: nil)+ due = Date.current + day_offset++ @family.recurring_transactions.create!(+ name: name,+ account: @account,+ amount: amount,+ currency: "USD",+ expected_day_of_month: due.day,+ anchor_date: due,+ last_occurrence_date: due,+ next_expected_date: due,+ status: "active",+ manual: true+ )+ end++ def create_entry(amount:, date:, name:)+ @account.entries.create!(+ date: date,+ amount: amount,+ currency: "USD",+ name: name,+ entryable: Transaction.new+ )+ end+enddiff --git a/test/models/recurring_transaction/identifier_test.rb b/test/models/recurring_transaction/identifier_test.rbindex 55268e05ac..9fb152a415 100644--- a/test/models/recurring_transaction/identifier_test.rb+++ b/test/models/recurring_transaction/identifier_test.rb@@ -7,6 +7,153 @@ class RecurringTransaction::IdentifierTest < ActiveSupport::TestCase@family.recurring_transactions.destroy_allend+ test "candidate_patterns offers undeclared recurring shapes and skips claimed, junk, and wrong-sign ones" do+ account = @family.accounts.first++ # An undeclared recurring charge: two occurrences on the same day.+ 2.times do |i|+ account.entries.create!(+ date: (i + 1).months.ago.to_date,+ amount: 45.00,+ currency: "USD",+ name: "City Water",+ entryable: Transaction.create!(category: categories(:food_and_drink))+ )+ end++ # A recurring deposit: inflow, so an income candidate only.+ 2.times do |i|+ account.entries.create!(+ date: (i + 1).months.ago.to_date,+ amount: -1840.00,+ currency: "USD",+ name: "ACME PAYROLL",+ entryable: Transaction.create!(category: categories(:food_and_drink))+ )+ end++ # A penny sweep recurs but is never worth offering.+ 2.times do |i|+ account.entries.create!(+ date: (i + 1).months.ago.to_date,+ amount: 0.01,+ currency: "USD",+ name: "To Car Vault",+ entryable: Transaction.create!(category: categories(:food_and_drink))+ )+ end++ # An already-declared charge must not be re-offered.+ 2.times do |i|+ account.entries.create!(+ date: (i + 1).months.ago.to_date,+ amount: 90.00,+ currency: "USD",+ name: "Internet Co",+ entryable: Transaction.create!(category: categories(:food_and_drink))+ )+ end+ @family.recurring_transactions.create!(+ name: "Internet Co",+ account: account,+ amount: 90.00,+ currency: "USD",+ expected_day_of_month: 15,+ last_occurrence_date: 1.month.ago.to_date,+ next_expected_date: 1.month.from_now.to_date,+ status: "active",+ manual: true+ )++ bill_names = @identifier.candidate_patterns(sign: :outflow).map { |pattern| pattern[:name] }+ income_names = @identifier.candidate_patterns(sign: :inflow).map { |pattern| pattern[:name] }++ assert_includes bill_names, "City Water"+ assert_not_includes bill_names, "ACME PAYROLL", "inflows are not bill candidates"+ assert_not_includes bill_names, "To Car Vault", "sub-dollar patterns are junk"+ assert_not_includes bill_names, "Internet Co", "declared series are not re-offered"+ assert_equal [ "ACME PAYROLL" ], income_names+ end++ test "income_source_candidates surfaces a variable weekly paycheck the pattern gate cannot see" do+ account = @family.accounts.first++ # Weekly pay, hours-driven amounts: no amount cluster, no stable day of month.+ [ [ 63, 1199.0 ], [ 56, 1393.75 ], [ 49, 1996.81 ], [ 42, 434.95 ], [ 35, 1254.77 ] ].each do |days_ago, amount|+ account.entries.create!(+ date: days_ago.days.ago.to_date,+ amount: -amount,+ currency: "USD",+ name: "ACME PAYROLL",+ entryable: Transaction.create!(category: categories(:food_and_drink))+ )+ end++ # Interest pennies recur but are never a payday.+ 2.times do |i|+ account.entries.create!(+ date: (i + 1).months.ago.end_of_month,+ amount: -0.31,+ currency: "USD",+ name: "Interest earned",+ entryable: Transaction.create!(category: categories(:food_and_drink))+ )+ end++ candidates = @identifier.income_source_candidates++ assert_equal [ "ACME PAYROLL" ], candidates.map { |candidate| candidate[:name] }+ assert_equal 5, candidates.first[:occurrence_count]+ assert @identifier.candidate_patterns(sign: :inflow).none? { |pattern| pattern[:occurrence_count] == 5 },+ "the amount-cluster path cannot see the whole variable-pay source; the source path must"+ end++ test "income_source_candidates skips sources already declared as income regardless of amount" do+ account = @family.accounts.first++ [ [ 40, 1500.0 ], [ 26, 900.0 ], [ 12, 2100.0 ] ].each do |days_ago, amount|+ account.entries.create!(+ date: days_ago.days.ago.to_date,+ amount: -amount,+ currency: "USD",+ name: "ACME PAYROLL",+ entryable: Transaction.create!(category: categories(:food_and_drink))+ )+ end++ @family.recurring_transactions.create!(+ name: "ACME PAYROLL",+ account: account,+ amount: -1800.00,+ currency: "USD",+ bill_type: "income",+ expected_day_of_month: 15,+ last_occurrence_date: 12.days.ago.to_date,+ next_expected_date: Date.current + 2,+ status: "active",+ manual: true+ )++ assert_empty @identifier.income_source_candidates+ end++ test "candidate_patterns needs only two consistent occurrences while identify still needs three" do+ account = @family.accounts.first++ 2.times do |i|+ account.entries.create!(+ date: (i + 1).months.ago.to_date,+ amount: 45.00,+ currency: "USD",+ name: "City Water",+ entryable: Transaction.create!(category: categories(:food_and_drink))+ )+ end++ assert_equal 1, @identifier.candidate_patterns(sign: :outflow).size+ assert_equal 0, @identifier.identify_recurring_patterns+ end+test "identifies recurring pattern with transactions on similar days mid-month" doaccount = @family.accounts.firstmerchant = merchants(:netflix)@@ -79,14 +226,15 @@ class RecurringTransaction::IdentifierTest < ActiveSupport::TestCaseaccount = @family.accounts.firstmerchant = merchants(:netflix)- # Create 3 transactions on days 28, 29, 30, 31, 1, 2 (should cluster with circular distance)+ # Days 30, 31, 1 and 2: all within the 2-day tolerance of the expected+ # day ON THE CIRCLE, which is what makes a month-boundary biller one+ # pattern. (A wider wobble is deliberately no longer a pattern:+ # consistency is per-occurrence, not on average.)dates = [- 3.months.ago.end_of_month - 3.days, # Day 28- 2.months.ago.end_of_month - 2.days, # Day 29- 2.months.ago.end_of_month - 1.day, # Day 30- 1.month.ago.end_of_month, # Day 31- Date.current.beginning_of_month, # Day 1- Date.current.beginning_of_month + 1.day # Day 2+ Date.new(2026, 5, 30),+ Date.new(2026, 5, 31),+ Date.new(2026, 7, 1),+ Date.new(2026, 8, 2)]dates.each do |date|@@ -103,7 +251,7 @@ class RecurringTransaction::IdentifierTest < ActiveSupport::TestCase)end- patterns_count = @identifier.identify_recurring_patterns+ patterns_count = travel_to(Date.new(2026, 8, 13)) { @identifier.identify_recurring_patterns }assert_equal 1, patterns_count, "Should identify pattern with circular clustering at month boundary"assert_equal 1, @family.recurring_transactions.count@@ -234,10 +382,12 @@ class RecurringTransaction::IdentifierTest < ActiveSupport::TestCaseassert_equal names.size, @family.recurring_transactions.where(name: names).countend- test "keeps automatic recurring lookup amount-scoped" do+ test "claims the nearest existing series per amount cluster without per-pattern lookups" doaccount = @family.accounts.firstname = "Tiered Performance Subscription"+ # Two tiers under one identity: the second carries a dedup_scope+ # discriminator, exactly as the detector stamps it.recurring_transactions = [ 40, 55 ].map do |amount|create_name_pattern_entries(account: account,@@ -250,6 +400,7 @@ class RecurringTransaction::IdentifierTest < ActiveSupport::TestCaseaccount: account,name: name,amount: amount,+ dedup_scope: amount == 40 ? "" : amount.to_s,currency: "USD",expected_day_of_month: 5,last_occurrence_date: 4.months.ago.to_date,@@ -428,6 +579,91 @@ class RecurringTransaction::IdentifierTest < ActiveSupport::TestCaseendend+ # A weekly cadence lands on a weekday, not near one day of the month, so the+ # variance refresh must keep every weekly payment instead of only the ones+ # that happen to sit within two days of expected_day_of_month.+ test "updates manual weekly variance from every payment on the series' weekday" do+ travel_to Date.new(2026, 6, 20) do+ account = @family.accounts.first+ name = "Weekly Lawn Service"+ fridays = [ Date.new(2026, 5, 29), Date.new(2026, 6, 5), Date.new(2026, 6, 12), Date.new(2026, 6, 19) ]++ recurring = @family.recurring_transactions.create!(+ account: account,+ name: name,+ amount: 40,+ currency: "USD",+ expected_day_of_month: fridays.first.day,+ anchor_date: fridays.first,+ last_occurrence_date: fridays.first,+ next_expected_date: fridays.second,+ occurrence_count: 0,+ status: "active",+ manual: true+ )+ RecurringTransaction::FrequencyPreset.apply(recurring, preset: "weekly", weekday: 5)+ recurring.save!++ fridays.each do |date|+ account.entries.create!(+ date: date,+ amount: 40,+ currency: "USD",+ name: name,+ entryable: Transaction.create!(category: categories(:food_and_drink))+ )+ end++ assert_no_difference -> { @family.recurring_transactions.count } do+ @identifier.identify_recurring_patterns+ end++ recurring.reload+ assert_equal 4, recurring.occurrence_count,+ "every Friday payment counts, including the ones across the month boundary"+ assert_equal fridays.last, recurring.last_occurrence_date+ end+ end++ # The next-due bookkeeping and the regenerated occurrences must agree: when+ # detection observes a day shift, next_expected_date has to follow the new+ # day immediately, not one detection run later.+ test "a detected day shift moves next_expected_date onto the new day" do+ travel_to Date.new(2026, 6, 20) do+ account = @family.accounts.first+ name = "Shifted Gym Membership"+ recurring = @family.recurring_transactions.create!(+ account: account,+ name: name,+ amount: 55,+ currency: "USD",+ expected_day_of_month: 5,+ last_occurrence_date: Date.new(2026, 5, 5),+ next_expected_date: Date.new(2026, 7, 5),+ occurrence_count: 3,+ status: "active",+ manual: false+ )++ [ Date.new(2026, 4, 12), Date.new(2026, 5, 12), Date.new(2026, 6, 12) ].each do |date|+ account.entries.create!(+ date: date,+ amount: 55,+ currency: "USD",+ name: name,+ entryable: Transaction.create!(category: categories(:food_and_drink))+ )+ end++ @identifier.identify_recurring_patterns++ recurring.reload+ assert_equal 12, recurring.expected_day_of_month+ assert_equal 12, recurring.next_expected_date.day,+ "the persisted next due date must use the newly detected day"+ end+ end+test "circular_distance calculates correct distance for days near month boundary" do# Test wrapping: day 31 to day 1 should be distance 1 (31 -> 1 is one day forward)distance = @identifier.send(:circular_distance, 31, 1)@@ -466,6 +702,134 @@ class RecurringTransaction::IdentifierTest < ActiveSupport::TestCaseassert_not @identifier.send(:days_cluster_together?, days)end+ test "scattered days are not a recurring pattern, whatever their average" do+ # Charges on the 3rd, 10th and 16th averaged out under the old std-dev+ # gate; per-occurrence consistency rejects them.+ account = @family.accounts.first+ [ [ 0, 3 ], [ 1, 10 ], [ 2, 16 ] ].each do |months_ago, day|+ transaction = Transaction.create!(category: categories(:food_and_drink))+ account.entries.create!(+ date: months_ago.months.ago.beginning_of_month + (day - 1).days,+ amount: 30, currency: "USD", name: "SCATTERED CHARGES",+ entryable: transaction+ )+ end++ assert_no_difference -> { @family.recurring_transactions.count } do+ @identifier.identify_recurring_patterns+ end+ end++ test "short-month clamping still reads as the same day" do+ account = @family.accounts.first+ # A day-30 bill: Feb lands on the 28th, two away on the circle -- in.+ [ Date.new(2026, 1, 30), Date.new(2026, 2, 28), Date.new(2026, 3, 30) ].each do |date|+ transaction = Transaction.create!(category: categories(:food_and_drink))+ account.entries.create!(+ date: date, amount: 55, currency: "USD", name: "MONTH END BILL",+ entryable: transaction+ )+ end++ travel_to Date.new(2026, 4, 10) do+ assert_difference -> { @family.recurring_transactions.count }, 1 do+ @identifier.identify_recurring_patterns+ end+ end+ end++ test "a price change within tolerance stays one series" do+ account = @family.accounts.first+ recurring = @family.recurring_transactions.create!(+ account: account,+ name: "Fiber Internet",+ amount: 79.99,+ currency: "USD",+ expected_day_of_month: 5,+ last_occurrence_date: 4.months.ago.to_date,+ next_expected_date: 1.month.from_now.to_date,+ occurrence_count: 3,+ status: "active"+ )++ # Price crept to 81.99 (2.5%): same obligation, must not fork a new row.+ create_name_pattern_entries(account: account, name: "Fiber Internet", amount: 81.99, day: 5)++ assert_no_difference -> { @family.recurring_transactions.count } do+ @identifier.identify_recurring_patterns+ end++ recurring.reload+ assert_equal 79.99, recurring.amount, "amount updates are the price-change detector's call, not detection's"+ assert_equal 81.99, recurring.expected_amount_min+ assert_equal 81.99, recurring.expected_amount_max+ end++ test "new detections land as suggested and stamp dedup_scope when the identity is taken" do+ account = @family.accounts.first+ @family.recurring_transactions.create!(+ account: account,+ name: "STREAMCO",+ amount: 5.99,+ currency: "USD",+ expected_day_of_month: 8,+ last_occurrence_date: 4.months.ago.to_date,+ next_expected_date: 1.month.from_now.to_date,+ occurrence_count: 3,+ status: "active"+ )++ # A second, genuinely different tier: far outside tolerance of 5.99.+ create_name_pattern_entries(account: account, name: "STREAMCO", amount: 24.99, day: 21)++ assert_difference -> { @family.recurring_transactions.count }, 1 do+ @identifier.identify_recurring_patterns+ end++ created = @family.recurring_transactions.order(:created_at).last+ assert_equal "suggested", created.status+ assert_equal "24.99", created.dedup_scope+ assert_not created.manual?+ end++ test "detection never recreates a manual bill or a dismissed one" do+ account = @family.accounts.first++ manual = @family.recurring_transactions.create!(+ account: account,+ name: "Declared Rent",+ amount: 2150,+ currency: "USD",+ expected_day_of_month: 5,+ last_occurrence_date: 2.months.ago.to_date,+ next_expected_date: 1.month.from_now.to_date,+ occurrence_count: 1,+ status: "active",+ manual: true+ )+ create_name_pattern_entries(account: account, name: "Declared Rent", amount: 2150, day: 5)++ dismissed = @family.recurring_transactions.create!(+ account: account,+ name: "Not A Bill",+ amount: 12.50,+ currency: "USD",+ expected_day_of_month: 5,+ last_occurrence_date: 2.months.ago.to_date,+ next_expected_date: 1.month.from_now.to_date,+ occurrence_count: 3,+ status: "ended"+ )+ create_name_pattern_entries(account: account, name: "Not A Bill", amount: 12.50, day: 5)++ assert_no_difference -> { @family.recurring_transactions.count } do+ @identifier.identify_recurring_patterns+ end++ assert_equal "ended", dismissed.reload.status+ assert manual.reload.manual?+ end+privatedef create_name_pattern_entries(account:, name:, amount:, day:)[ 0, 1, 2 ].each do |months_ago|@@ -496,4 +860,64 @@ class RecurringTransaction::IdentifierTest < ActiveSupport::TestCasequeriesend++ # `manual` is set at creation and no edit flips it, so a detected bill whose+ # due day the user corrected by hand was reverted by the next sync, which+ # also regenerated its future occurrences on the rejected day.+ test "detection leaves a hand-pinned schedule alone" do+ series = detected_monthly_series++ RecurringTransaction::FrequencyPreset.apply(series, preset: "monthly", day_of_month: 20)+ series.pin_schedule+ series.save!++ RecurringTransaction::Identifier.new(Family.find(@family.id)).identify_recurring_patterns+ series = RecurringTransaction.find(series.id)++ assert_equal 20, series.recurrence_rules.first.day_of_month,+ "the day the user set survives the next sync"+ assert_equal 20, series.expected_day_of_month,+ "and the series reports the day the user set, not the observed one"+ end++ # Negative control: without the pin, detection still corrects the due day to+ # the day the charges actually land on. Without this the guard above could+ # pass by simply switching the feature off.+ test "detection still tracks the observed day when nothing is pinned" do+ series = detected_monthly_series+ observed_day = series.expected_day_of_month++ RecurringTransaction::FrequencyPreset.apply(series, preset: "monthly", day_of_month: 20)+ series.save!+ assert_equal 20, RecurringTransaction.find(series.id).expected_day_of_month++ RecurringTransaction::Identifier.new(Family.find(@family.id)).identify_recurring_patterns+ series = RecurringTransaction.find(series.id)++ assert_not series.schedule_pinned?+ assert_equal observed_day, series.expected_day_of_month,+ "an unpinned series is still corrected to the day its charges land on"+ end++ private+ # Three same-day charges inside the detection window: the smallest thing+ # the Identifier will turn into a monthly series.+ def detected_monthly_series+ account = @family.accounts.first+ anchor = Date.current.beginning_of_month + 8++ 3.times do |i|+ account.entries.create!(+ date: anchor - i.months,+ amount: 45.00, currency: "USD", name: "City Water",+ entryable: Transaction.create!(category: categories(:food_and_drink))+ )+ end++ RecurringTransaction::Identifier.new(@family).identify_recurring_patterns+ @family.recurring_transactions.find_by(name: "City Water").tap do |series|+ raise "fixture did not produce a detected series" if series.nil?+ raise "fixture produced a manual series" if series.manual?+ end+ endenddiff --git a/test/models/recurring_transaction/matcher_test.rb b/test/models/recurring_transaction/matcher_test.rbnew file mode 100644index 0000000000..f529d5321a--- /dev/null+++ b/test/models/recurring_transaction/matcher_test.rb@@ -0,0 +1,359 @@+require "test_helper"++class RecurringTransaction::MatcherTest < ActiveSupport::TestCase+ Matcher = RecurringTransaction::Matcher++ def setup+ @family = families(:dylan_family)+ @account = accounts(:depository)+ @family.recurring_transactions.destroy_all+ @matcher = Matcher.new(@family)+ end++ # Candidate collection excludes entries that already have a CONFIRMED+ # allocation, not a suggested one, so an unreviewed suggestion leaves its+ # charge eligible. With two series competing for it, a second run could stack+ # a second allocation on the same charge. What stops it is that the first+ # suggestion has already spoken for the entry's whole amount.+ test "repeat runs never stack a second allocation on one charge" do+ create_series(name: "Streaming Service", amount: 15.99, day_offset: 0, dedup_scope: "a")+ create_series(name: "Streaming Service", amount: 15.99, day_offset: 0, dedup_scope: "b")+ entry = create_entry(amount: 15.99, date: Date.current, name: "Streaming Service")++ 3.times { Matcher.new(@family).run! }++ allocations = RecurringAllocation.where(entry_id: entry.id)+ assert_equal 1, allocations.count,+ "one charge must not fund two bills just because the first link is unreviewed"+ assert_equal 15.99, allocations.sum(:allocated_amount).to_f+ end++ test "a merchant charge near the expected amount auto-links and settles the bill" do+ # The mission's own example: Comcast expected at $119.99, charged $121.74.+ series = create_series(name: nil, merchant: merchants(:netflix), amount: 119.99, day_offset: 2)+ occurrence = series.recurring_occurrences.order(:due_on).first+ entry = create_entry(amount: 121.74, date: Date.current, merchant: merchants(:netflix))++ assert_equal 1, @matcher.run!++ allocation = occurrence.allocations.sole+ assert allocation.allocation_confirmed?+ assert allocation.from_auto_matched?+ assert_equal entry.id, allocation.entry_id+ assert_operator allocation.match_confidence, :>=, 0.85+ assert allocation.match_signals.key?("merchant")+ assert occurrence.reload.paid?, "single in-tolerance charge IS the bill"+ end++ test "a weaker match lands in the review queue, not on the bill" do+ # A week overdue, paid today at the edge of the amount band: plausible,+ # not certain.+ series = create_series(name: "CITY WATER", amount: 80, day_offset: -7)+ occurrence = series.recurring_occurrences.order(:due_on).first+ create_entry(amount: 85.50, date: Date.current, name: "CITY WATER")++ @matcher.run!++ allocation = occurrence.allocations.sole+ assert allocation.allocation_suggested?+ assert occurrence.reload.scheduled?, "suggestions never move paid state"+ end++ test "two look-alike bills competing for one charge demote to suggestions" do+ twin_a = create_series(name: "GYM", amount: 40, day_offset: -3)+ twin_b = create_series(name: "GYM", amount: 40, day_offset: -3, dedup_scope: "second")+ create_entry(amount: 40, date: Date.current - 3, name: "GYM")++ @matcher.run!++ states = (twin_a.recurring_occurrences.order(:due_on).first.allocations.to_a ++ twin_b.recurring_occurrences.order(:due_on).first.allocations.to_a).map(&:state)+ assert_equal [ "suggested" ], states.uniq+ assert_equal 1, states.size, "one entry is proposed once, to the better candidate"+ end++ test "a rejected pair is never suggested again" do+ series = create_series(name: "CITY WATER", amount: 80, day_offset: -7)+ occurrence = series.recurring_occurrences.order(:due_on).first+ create_entry(amount: 85.50, date: Date.current, name: "CITY WATER")++ @matcher.run!+ suggestion = occurrence.allocations.sole+ RecurringTransaction::Allocator.new(occurrence).reject_suggestion!(suggestion)++ assert_equal 0, @matcher.run!+ assert_equal 0, occurrence.reload.allocations.count+ end++ test "a pending charge is suggested at most, never auto-linked" do+ series = create_series(name: nil, merchant: merchants(:netflix), amount: 119.99, day_offset: 1)+ occurrence = series.recurring_occurrences.order(:due_on).first+ create_entry(amount: 119.99, date: Date.current, merchant: merchants(:netflix),+ extra: { "simplefin" => { "pending" => true } })++ @matcher.run!++ assert occurrence.allocations.sole.allocation_suggested?+ end++ # The payment review queue is where suggestions land, and income review has+ # no home there: a paycheck is not a bill anyone needs to approve paying.+ test "an income series never suggests, while the same shape on a bill does" do+ income = create_series(name: "ACME PAYROLL", amount: -1840, day_offset: -7, bill_type: "income")+ bill = create_series(name: "CITY WATER", amount: 80, day_offset: -7)+ create_entry(amount: -1900, date: Date.current, name: "ACME PAYROLL")+ create_entry(amount: 85.50, date: Date.current, name: "CITY WATER")++ @matcher.run!++ assert_equal 0, income.recurring_occurrences.order(:due_on).first.allocations.count,+ "a near-miss deposit must not queue income for payment review"+ assert bill.recurring_occurrences.order(:due_on).first.allocations.sole.allocation_suggested?,+ "the identical near-miss on a bill still suggests"+ end++ test "an exact income match still auto-links and closes the payday" do+ income = create_series(name: "ACME PAYROLL", amount: -1840, day_offset: 0, bill_type: "income")+ occurrence = income.recurring_occurrences.order(:due_on).first+ create_entry(amount: -1840, date: Date.current, name: "ACME PAYROLL")++ assert_equal 1, @matcher.run!++ assert occurrence.allocations.sole.allocation_confirmed?+ assert occurrence.reload.paid?, "the exact tier is what advances the paycheck planner"+ end++ test "weekly windows clamp so one payment cannot satisfy two weeks" do+ series = create_series(name: "CLEANER", amount: 100, day_offset: 0, preset: "weekly")+ occurrences = series.recurring_occurrences.order(:due_on).limit(2).to_a+ entry = create_entry(amount: 100, date: occurrences.first.due_on, name: "CLEANER")++ @matcher.run!++ linked = RecurringAllocation.where(entry: entry)+ assert_equal 1, linked.count+ assert_equal occurrences.first.id, linked.sole.recurring_occurrence_id+ end++ test "an overdue occurrence stays matchable, and a very late payment queues for review" do+ series = create_series(name: "OLD RENT", amount: 500, day_offset: -20)+ occurrence = series.recurring_occurrences.order(:due_on).first+ assert_equal :overdue, occurrence.derived_state++ create_entry(amount: 500, date: Date.current, name: "OLD RENT")++ @matcher.run!++ # Three weeks of date distance drags an otherwise perfect match below the+ # auto-link bar on purpose: suggest, never silently guess. One click+ # settles it.+ suggestion = occurrence.allocations.sole+ assert suggestion.allocation_suggested?++ RecurringTransaction::Allocator.new(occurrence).confirm_suggestion!(suggestion)+ assert occurrence.reload.paid?+ end++ test "a months-deep backlog matches each payment to its own occurrence" do+ # The Curbside bug: every overdue occurrence's window reaches today, so+ # without nearest-occurrence assignment each exact payment gains+ # same-series runner-ups and demotes to a discarded suggestion.+ series = create_series(name: "CURBSIDE CUTS & SHAVE", amount: 150, day_offset: -19)+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 100)++ past = series.recurring_occurrences.where("due_on <= ?", Date.current).order(:due_on).to_a+ assert_operator past.size, :>=, 3+ past.each { |occurrence| create_entry(amount: 150, date: occurrence.due_on, name: "CURBSIDE CUTS & SHAVE") }++ @matcher.run_backfill!++ past.each do |occurrence|+ assert occurrence.reload.paid?, "#{occurrence.due_on} must close against its own payment"+ assert_equal occurrence.due_on, occurrence.allocations.sole.paid_on+ end+ end++ test "backfill mode writes confirmed history only, never suggestions" do+ series = create_series(name: "CITY WATER", amount: 80, day_offset: -7)+ exact_series = create_series(name: "POWER CO", amount: 60, day_offset: 2)+ create_entry(amount: 85.50, date: Date.current, name: "CITY WATER")+ create_entry(amount: 60, date: Date.current, name: "POWER CO")++ @matcher.run_backfill!++ assert_equal 0, series.recurring_occurrences.order(:due_on).first.allocations.count+ assert exact_series.recurring_occurrences.order(:due_on).first.allocations.sole.allocation_confirmed?+ end++ test "repair re-attaches an allocation whose entry was replaced under it" do+ series = create_series(name: "POWER CO", amount: 60, day_offset: 2)+ occurrence = series.recurring_occurrences.order(:due_on).first+ original = create_entry(amount: 60, date: Date.current, name: "POWER CO")+ @matcher.run!+ allocation = occurrence.allocations.sole++ original.destroy!+ assert_nil allocation.reload.entry_id++ replacement = create_entry(amount: 60, date: allocation.paid_on, name: "POWER CO POSTED")+ @matcher.repair_orphans!++ assert_equal replacement.id, allocation.reload.entry_id+ end++ test "manually attaching an alien-named entry teaches an alias" do+ series = create_series(name: "Watson Property", amount: 2150, day_offset: 5)+ occurrence = series.recurring_occurrences.order(:due_on).first+ entry = create_entry(amount: 2150, date: Date.current + 4, name: "WPM LLC WEB PMT")++ RecurringTransaction::Allocator.new(occurrence).allocate!(entry: entry)++ assert_includes series.reload.matcher_hints["name_aliases"], "WPM LLC WEB PMT"+ end++ test "a single out-of-band settlement widens the learned tolerance; a partial teaches nothing" do+ series = create_series(name: "POWER CO", amount: 100, day_offset: 5)+ occurrence = series.recurring_occurrences.order(:due_on).first+ settlement = create_entry(amount: 118, date: Date.current + 4, name: "POWER CO")+ RecurringTransaction::Allocator.new(occurrence).allocate!(entry: settlement)+ assert_in_delta 18.0, series.reload.matcher_hints["learned_tolerance_pct"], 0.1++ rent = create_series(name: "BIG RENT", amount: 2150, day_offset: 5)+ rent_occurrence = rent.recurring_occurrences.order(:due_on).first+ partial = create_entry(amount: 537.50, date: Date.current + 4, name: "BIG RENT")+ RecurringTransaction::Allocator.new(rent_occurrence).allocate!(entry: partial)++ assert_nil rent.reload.matcher_hints["learned_tolerance_pct"],+ "a rent installment is not evidence rent varies"+ end++ test "confirming a suggestion settles the bill" do+ series = create_series(name: "CITY WATER", amount: 80, day_offset: -7)+ occurrence = series.recurring_occurrences.order(:due_on).first+ create_entry(amount: 85.50, date: Date.current, name: "CITY WATER")+ @matcher.run!++ RecurringTransaction::Allocator.new(occurrence).confirm_suggestion!(occurrence.allocations.sole)++ assert occurrence.reload.paid?+ assert occurrence.allocations.sole.from_user_confirmed?+ end++ # explain is what lets a surface show a person WHY something matched. The+ # payment picker used to rank by amount distance alone and never consult the+ # engine, which is how a Twitch charge could outrank the 7-Eleven charge for+ # a 7-Eleven bill.+ test "explain returns the signals behind a strong match" do+ series = create_series(name: nil, merchant: merchants(:netflix), amount: 15.99, day_offset: 0)+ occurrence = series.recurring_occurrences.order(:due_on).first+ entry = create_entry(amount: 15.99, date: occurrence.due_on, merchant: merchants(:netflix))++ explanation = @matcher.explain(occurrence, entry)++ assert_not_nil explanation+ assert_equal 0.40, explanation.signals[:merchant]+ assert_equal 0.30, explanation.signals[:amount], "an exact amount scores the full 0.30"+ assert_equal 0.20, explanation.signals[:date], "landing on the due date scores the full 0.20"+ assert_operator explanation.confidence, :>=, Matcher::EXACT_TIER+ end++ test "explain refuses an entry from another merchant outright" do+ series = create_series(name: nil, merchant: merchants(:netflix), amount: 15.99, day_offset: 0)+ occurrence = series.recurring_occurrences.order(:due_on).first+ other = create_entry(amount: 15.99, date: occurrence.due_on, merchant: merchants(:amazon))++ assert_nil @matcher.explain(occurrence, other),+ "a same-amount same-day charge from a different merchant is not a weak match, it is not a match"+ end++ test "explain refuses an entry outside the date window" do+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0)+ occurrence = series.recurring_occurrences.order(:due_on).first+ entry = create_entry(amount: 80, date: occurrence.due_on - 60, name: "CITY WATER")++ assert_nil @matcher.explain(occurrence, entry)+ end++ test "explain refuses an amount outside the tolerance band" do+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0)+ occurrence = series.recurring_occurrences.order(:due_on).first+ entry = create_entry(amount: 400, date: occurrence.due_on, name: "CITY WATER")++ assert_nil @matcher.explain(occurrence, entry),+ "outside tolerance the score is a flat zero, and zero must not reach a picker"+ end+++ # Allocations store magnitudes, entries store signs. A magnitude-only lookup+ # never matched a reposted paycheck, so orphaned income stayed orphaned.+ test "repair finds a reposted income entry by its signed amount" do+ series = create_series(name: "PAYCHECK CO", amount: -1840, day_offset: 0, bill_type: "income")+ occurrence = series.recurring_occurrences.order(:due_on).first+ original = create_entry(amount: -1840, date: Date.current, name: "PAYCHECK CO")+ @matcher.run!+ allocation = occurrence.allocations.sole++ original.destroy!+ assert_nil allocation.reload.entry_id++ replacement = create_entry(amount: -1840, date: allocation.paid_on, name: "PAYCHECK CO POSTED")+ @matcher.repair_orphans!++ assert_equal replacement.id, allocation.reload.entry_id+ end++ # Same day, same amount, different merchant is a coincidental twin, not the+ # bill's own repost, and attaching it reports the bill paid by a stranger.+ test "repair refuses a same-amount entry that is not the series' identity" do+ series = create_series(name: "POWER CO", amount: 60, day_offset: 0)+ occurrence = series.recurring_occurrences.order(:due_on).first+ original = create_entry(amount: 60, date: Date.current, name: "POWER CO")+ @matcher.run!+ allocation = occurrence.allocations.sole++ original.destroy!+ create_entry(amount: 60, date: allocation.paid_on, name: "SUSHI PALACE")++ @matcher.repair_orphans!++ assert_nil allocation.reload.entry_id, "a stranger with the same price is not the bill"+ end++ private+ def create_series(amount:, day_offset:, name: nil, merchant: nil, dedup_scope: "", preset: "monthly", bill_type: "bill")+ due = Date.current + day_offset++ series = @family.recurring_transactions.create!(+ name: name,+ merchant: merchant,+ account: @account,+ amount: amount,+ currency: "USD",+ bill_type: bill_type,+ dedup_scope: dedup_scope,+ expected_day_of_month: due.day,+ anchor_date: due,+ last_occurrence_date: due,+ next_expected_date: due,+ status: "active",+ manual: true+ )++ if preset != "monthly"+ RecurringTransaction::FrequencyPreset.apply(series, preset: preset, weekday: due.wday)+ series.save!+ end++ series+ end++ def create_entry(amount:, date:, name: "charge", merchant: nil, extra: {})+ @account.entries.create!(+ date: date,+ amount: amount,+ currency: "USD",+ name: name,+ entryable: Transaction.new(merchant: merchant, extra: extra)+ )+ end+enddiff --git a/test/models/recurring_transaction/occurrence_generator_test.rb b/test/models/recurring_transaction/occurrence_generator_test.rbnew file mode 100644index 0000000000..eed354e8ba--- /dev/null+++ b/test/models/recurring_transaction/occurrence_generator_test.rb@@ -0,0 +1,102 @@+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+enddiff --git a/test/models/recurring_transaction/paycheck_planner_test.rb b/test/models/recurring_transaction/paycheck_planner_test.rbnew file mode 100644index 0000000000..faafc8bff2--- /dev/null+++ b/test/models/recurring_transaction/paycheck_planner_test.rb@@ -0,0 +1,428 @@+require "test_helper"++class RecurringTransaction::PaycheckPlannerTest < ActiveSupport::TestCase+ Planner = RecurringTransaction::PaycheckPlanner++ def setup+ @family = families(:dylan_family)+ @user = users(:family_admin)+ @account = accounts(:depository)+ @family.recurring_transactions.destroy_all+ end++ test "no declared income means no plan" do+ create_series(name: "Rent", amount: 2150, due: Date.current + 10)++ assert_nil Planner.new(@family, user: @user).plan+ end++ test "auto-detected inflows never define paydays" do+ penny = create_series(name: "To Car Vault", amount: -0.01, due: Date.current + 2, income: true)+ penny.update!(manual: false)+ create_series(name: "Rent", amount: 2150, due: Date.current + 10)++ assert_nil Planner.new(@family, user: @user).plan,+ "a recurring one-cent transfer is income by sign and a paycheck by nothing"+ end++ test "periods slice by paycheck and apportion bills to their due dates" do+ first_payday = Date.current + 3+ create_series(name: "Paycheck", amount: -1840, due: first_payday, preset: "weekly", income: true)+ rent_due = Date.current + 17+ rent = create_series(name: "Rent", amount: 2150, due: rent_due)+ create_series(name: "Internet", amount: 90, due: Date.current + 5)++ plan = Planner.new(@family, user: @user).plan(periods_limit: 3)++ assert_equal 4, plan.size, "today-to-first-paycheck plus three paychecks"+ assert_equal Date.current, plan.first.starts_on+ assert_equal 0, plan.first.income+ assert_equal 1840, plan[1].income++ rent_shares = plan.flat_map(&:items).select { |item| item.occurrence.recurring_transaction_id == rent.id }+ # Rent's own paycheck funds what it can; only the overflow it cannot cover+ # is reserved, out of the paycheck nearest before it.+ assert_equal 2, rent_shares.size, "one due share plus one reserve for the overflow"+ assert_equal 2150, rent_shares.sum(&:share), "shares reassemble the full obligation exactly"+ assert_equal 1, rent_shares.count(&:due_in_period)+ assert_equal 1840, rent_shares.find(&:due_in_period).share, "the due share is what its paycheck can fund"+ assert_equal 310, plan[2].reserved_total, "the paycheck just before rent holds the overflow"++ plan.each do |period|+ assert_equal period.income - period.obligation_total, period.remaining+ end+ end++ # The page states due and reserved separately and never their sum, so the+ # planner has to hand over both. Adding them back together must reproduce+ # obligation_total exactly, or the card's arithmetic stops reconciling.+ test "every period splits its obligations into due here and reserved for later" do+ first_payday = Date.current + 3+ create_series(name: "Paycheck", amount: -1840, due: first_payday, preset: "weekly", income: true)+ create_series(name: "Internet", amount: 90, due: first_payday + 2)+ create_series(name: "Rent", amount: 2150, due: Date.current + 17)++ plan = Planner.new(@family, user: @user).plan(periods_limit: 3)++ plan.each do |period|+ assert_equal period.items_due.sum(&:share), period.due_total+ assert_equal period.items_reserved.sum(&:share), period.reserved_total+ assert_equal period.due_total + period.reserved_total, period.obligation_total+ assert_equal period.income - period.due_total - period.reserved_total, period.remaining+ end++ internet_shares = plan.flat_map(&:items).select { |item| item.occurrence.recurring_transaction.name == "Internet" }+ assert_equal 90, internet_shares.sum(&:share), "the shares reassemble the bill"+ assert_equal 1, internet_shares.count(&:due_in_period),+ "a bill counts as due in exactly one window, and reserves earlier only what that window cannot fund"+ assert plan.any? { |period| period.due_total.positive? }+ assert plan.any? { |period| period.reserved_total.positive? }++ # Both lists render as a ledger with the date in a fixed left column, so+ # they have to descend in date order.+ plan.each do |period|+ [ period.items_due, period.items_reserved ].each do |list|+ dates = list.map { |item| item.occurrence.due_on }+ assert_equal dates.sort, dates+ end+ end+ end++ # The leading window is funded by cash already in hand, not by a paycheck,+ # and the page has to be able to say so instead of reporting "remaining".+ test "the window before the first paycheck is a bridge, not a paycheck" do+ create_series(name: "Paycheck", amount: -1840, due: Date.current + 3, preset: "weekly", income: true)+ create_series(name: "Streaming", amount: 20, due: Date.current + 1)++ plan = Planner.new(@family, user: @user).plan(periods_limit: 3)++ assert plan.first.bridge?+ assert_not plan.first.short?,+ "a $20 bill against $5,000 in the bank is not a shortfall, whatever the window earns"+ assert plan.drop(1).none?(&:bridge?), "a window that pays is never a bridge"+ end++ # A reserve has to come out of a paycheck. The leading window has no income by+ # definition, so charging it a share of a bill due after the next payday+ # reported it short by money it was never going to see, while telling the user+ # nothing was due in that window. Both figures were right; the model was not.+ test "the window before the first payday reserves nothing for later bills" do+ payday = Date.current + 3+ create_series(name: "Paycheck", amount: -1840, due: payday, preset: "weekly", income: true)+ create_series(name: "Rent", amount: 1450, due: payday + 3)++ plan = Planner.new(@family, user: @user).plan(periods_limit: 3)+ bridge = plan.first++ assert bridge.bridge?+ assert_equal 0, bridge.reserved_total,+ "nothing is reserved out of a window that receives no income"+ assert_equal 0, bridge.due_total, "and nothing falls due in it either"+ assert_not bridge.short?,+ "so it cannot be short: a window owing nothing is not a shortfall"+ end++ # The flip side: a bill that really does fall due before the first payday is+ # still the leading window's problem, because it is paid from cash in hand.+ test "the window before the first payday still carries what is due inside it" do+ payday = Date.current + 5+ create_series(name: "Paycheck", amount: -1840, due: payday, preset: "weekly", income: true)+ create_series(name: "Water", amount: 64, due: Date.current + 2)++ bridge = Planner.new(@family, user: @user).plan(periods_limit: 3).first++ assert_equal 64, bridge.due_total+ assert_equal 0, bridge.reserved_total+ assert_not bridge.short?, "the cash on hand covers it, so nothing is short"+ assert_equal 0, bridge.shortfall+ end++ # The reserve does not vanish, it moves to the paychecks that precede the bill.+ test "reserves land on the paychecks before the bill, and still reassemble it" do+ payday = Date.current + 3+ create_series(name: "Paycheck", amount: -1840, due: payday, preset: "weekly", income: true)+ rent = create_series(name: "Rent", amount: 2150, due: payday + 10)++ plan = Planner.new(@family, user: @user).plan(periods_limit: 3)+ shares = plan.flat_map(&:items).select { |item| item.occurrence.recurring_transaction_id == rent.id }++ assert_equal 2150, shares.sum(&:share), "the shares still reassemble the bill"+ assert plan.first.items.none? { |item| item.occurrence.recurring_transaction_id == rent.id },+ "and none of it is charged to the window before the first payday"+ assert_equal 310, plan[1].reserved_total, "the first paycheck holds what rent's own cannot fund"+ end++ # The user's own case: paid weekly with weekly bills, every bill inside its+ # own paycheck. The old even spread parked half of next week's bill in this+ # week's check anyway, so no week ever read as clean.+ test "bills covered by their own paycheck reserve nothing from earlier ones" do+ create_series(name: "Paycheck", amount: -1600, due: Date.current + 3, preset: "weekly", income: true)+ create_series(name: "Groceries", amount: 200, due: Date.current + 5, preset: "weekly")++ plan = Planner.new(@family, user: @user).plan(periods_limit: 3)+ paychecks = plan.reject(&:bridge?)++ assert_equal 3, paychecks.size+ paychecks.each do |period|+ assert_equal 200, period.due_total, "each week's bill lands in its own week"+ assert_equal 0, period.reserved_total,+ "a bill its own paycheck covers reserves nothing; the even spread would have parked next week's bill here"+ assert_equal 1400, period.remaining, "safe is simply income minus what is due"+ end+ end++ # A bill bigger than one paycheck is the one genuine reason to reserve, and+ # the reserve fills backward from the paycheck nearest the bill.+ test "a bill that outgrows its paycheck reserves the overflow from the nearest earlier one" do+ payday = Date.current + 3+ create_series(name: "Paycheck", amount: -1600, due: payday, preset: "weekly", income: true)+ rent = create_series(name: "Rent", amount: 2150, due: Date.current + 17)++ plan = Planner.new(@family, user: @user).plan(periods_limit: 3)++ rent_period = plan[3]+ assert_equal 1600, rent_period.due_total, "rent takes its whole paycheck"+ assert_equal 0, rent_period.remaining+ assert_not rent_period.short?, "the reserve upstream is what keeps it whole"++ assert_equal 550, plan[2].reserved_total, "the nearest earlier paycheck holds the overflow"+ assert_equal 0, plan[1].reserved_total, "the farther one is untouched: nearest fills first"++ shares = plan.flat_map(&:items).select { |item| item.occurrence.recurring_transaction_id == rent.id }+ assert_equal 2150, shares.sum(&:share), "the shares reassemble the bill"+ reserve = shares.find { |item| !item.due_in_period }+ assert_equal 2150, reserve.remaining_total, "the reserve names the whole bill it is a slice of"+ end++ # When even every earlier paycheck cannot absorb the overflow, the earliest+ # one takes the rest and goes short, so the plan is short today rather than+ # the week the bill arrives.+ test "overflow no paycheck can absorb lands on the earliest paycheck as its shortfall" do+ create_series(name: "Paycheck", amount: -400, due: Date.current + 3, preset: "weekly", income: true)+ create_series(name: "Rent", amount: 2150, due: Date.current + 17)++ plan = Planner.new(@family, user: @user).plan(periods_limit: 3)++ assert_equal 400, plan[3].due_total, "rent's own paycheck goes in whole"+ assert_equal 0, plan[3].remaining+ assert_equal 400, plan[2].reserved_total, "the nearer paycheck fills to its income and no further"+ assert_equal 0, plan[2].remaining+ assert_equal 1350, plan[1].reserved_total, "the earliest takes everything the others could not"+ assert plan[1].short?+ assert_equal 950, plan[1].shortfall, "short by exactly what three paychecks cannot cover"+ assert_equal 0, plan.first.reserved_total, "and the bridge window still never reserves"+ end++ # A paycheck arriving today makes the leading window a real pay period, so+ # bridge? has to read income rather than position.+ test "income landing today makes the leading window a paycheck" do+ create_series(name: "Paycheck", amount: -1840, due: Date.current, preset: "weekly", income: true)++ plan = Planner.new(@family, user: @user).plan(periods_limit: 3)++ assert_not plan.first.bridge?+ assert_equal 1840, plan.first.income+ end++ # "Which bill is making me short" has to answer with the obligation. The+ # slice a period carries is an artifact of how many paychecks the plan had+ # to spread it over.+ test "the largest obligation is named by what it costs, not by its slice" do+ create_series(name: "Paycheck", amount: -400, due: Date.current + 2, preset: "weekly", income: true)+ create_series(name: "Rent", amount: 2150, due: Date.current + 20)+ create_series(name: "Insurance", amount: 300, due: Date.current + 3)++ # The first paycheck, not the leading window: that one reserves nothing.+ period = Planner.new(@family, user: @user).plan(periods_limit: 3)[1]+ largest = period.largest_obligation++ assert_equal "Rent", largest.occurrence.recurring_transaction.name+ assert_equal 2150, largest.remaining_total+ assert largest.share < largest.remaining_total, "the slice is smaller than the bill it belongs to"+ end++ # The period is named by the income that opens it, because calling a pension+ # or an invoice a "paycheck" contradicts the user's own setup.+ test "a period carries the names of the income that opens it" do+ payday = Date.current + 2+ create_series(name: "Frito Lay", amount: -1200, due: payday, preset: "weekly", income: true)+ create_series(name: "Side work", amount: -300, due: payday, preset: "weekly", income: true)++ period = Planner.new(@family, user: @user).plan(periods_limit: 3)[1]++ assert_equal 1500, period.income+ assert_equal [ "Frito Lay", "Side work" ], period.income_sources.sort+ end++ # The income list and the plan used to read different sources for one fact,+ # so a series could name two different next paydays on one screen.+ test "next income per series comes from occurrences, not the stored column" do+ payday = Date.current + 5+ series = create_series(name: "Paycheck", amount: -1840, due: payday, preset: "weekly", income: true)+ series.update_columns(next_expected_date: Date.current - 1)++ planner = Planner.new(@family, user: @user)+ next_income = planner.next_income_by_series[series.id]++ assert_equal payday, next_income.due_on+ assert_equal planner.plan.find { |period| period.income.positive? }.starts_on, next_income.due_on,+ "the strip and the plan have to name the same day"+ end++ test "partial payments shrink the apportioned obligation" do+ create_series(name: "Paycheck", amount: -2000, due: Date.current + 2, preset: "weekly", income: true)+ rent = create_series(name: "Rent", amount: 2150, due: Date.current + 9)+ occurrence = rent.recurring_occurrences.order(:due_on).first+ RecurringTransaction::Allocator.new(occurrence).allocate!(amount: "1075")++ plan = Planner.new(@family, user: @user).plan+ rent_total = plan.flat_map(&:items)+ .select { |item| item.occurrence.recurring_transaction_id == rent.id }+ .sum(&:share)++ assert_equal 1075, rent_total, "only the remaining balance needs setting aside"+ end++ # Folding an unconvertible obligation in as zero inflates what the plan says+ # is safe to spend by exactly the amount the user cannot see.+ test "an obligation with no exchange rate is counted, not dropped" do+ create_series(name: "Paycheck", amount: -1840, due: Date.current + 3, preset: "weekly", income: true)+ foreign = @family.recurring_transactions.create!(+ name: "Tokyo storage", account: @account, amount: 50_000, currency: "JPY",+ bill_type: "bill", expected_day_of_month: (Date.current + 5).day,+ anchor_date: Date.current + 5, last_occurrence_date: Date.current + 5,+ next_expected_date: Date.current + 5, status: "active", manual: true+ )+ assert_equal 0, ExchangeRate.where(from_currency: "JPY", to_currency: "USD").count,+ "the scenario depends on there being no rate to find"++ planner = Planner.new(@family, user: @user)+ plan = planner.plan(periods_limit: 3)++ assert plan.present?+ assert foreign.recurring_occurrences.any?, "the obligation really was inside the window"+ assert planner.unconvertible_count.positive?,+ "the JPY obligation must be reported, not silently valued at zero"+ end++ # Generation lag can leave a lone materialized paycheck landing today; the+ # boundary list collapses to one date and there is no period to build.+ test "income due today with no later occurrences yields an empty plan rather than raising" do+ series = create_series(name: "Final paycheck", amount: -1840, due: Date.current, income: true)+ series.recurring_occurrences.where("due_on > ?", Date.current).delete_all++ assert_equal [], Planner.new(@family, user: @user).plan+ end++ test "a past-due open bill lands whole in the leading window" do+ create_series(name: "Paycheck", amount: -1840, due: Date.current + 7, preset: "weekly", income: true)+ overdue_due = Date.current - 3+ create_series(name: "Power", amount: 120, due: overdue_due)++ plan = Planner.new(@family, user: @user).plan(periods_limit: 2)++ shares = plan.flat_map(&:items).select { |item| item.occurrence.due_on == overdue_due }+ assert_equal 1, shares.size, "the overdue bill must appear exactly once"+ assert_equal 120, shares.sum(&:share), "its whole remaining amount is owed now"+ assert shares.first.due_in_period, "it is due money, not a reserve"+ assert_includes plan.first.items, shares.first, "and it belongs to the leading window"+ 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+ # who simply had a bill before payday. What decides it is the cash in hand,+ # which the code claimed to compare and never did.+ test "a bridge window is short only when the cash cannot cover it" do+ set_cash(40)+ create_series(name: "Paycheck", amount: -1840, due: Date.current + 5, preset: "weekly", income: true)+ create_series(name: "Water", amount: 64, due: Date.current + 2)++ bridge = Planner.new(@family, user: @user).plan(periods_limit: 3).first++ assert bridge.short?, "$64 due against $40 in the bank is a real shortfall"+ assert_equal 24, bridge.shortfall, "short by the gap, not by the whole bill"+ end++ test "a bridge window covered by cash reports what is left, not a shortfall" do+ set_cash(500)+ create_series(name: "Paycheck", amount: -1840, due: Date.current + 5, preset: "weekly", income: true)+ create_series(name: "Water", amount: 64, due: Date.current + 2)++ bridge = Planner.new(@family, user: @user).plan(periods_limit: 3).first++ assert_not bridge.short?+ assert_equal 436, bridge.cash_after_obligations+ end++ test "an unknown balance is not evidence of a shortfall" do+ @family.accounts.update_all(status: "disabled")+ create_series(name: "Paycheck", amount: -1840, due: Date.current + 5, preset: "weekly", income: true)+ create_series(name: "Water", amount: 64, due: Date.current + 2)++ bridge = Planner.new(@family, user: @user).plan(periods_limit: 3).first++ assert_nil bridge.cash_on_hand+ assert_not bridge.short?, "with no readable balance the window goes unjudged rather than flagged"+ assert_nil bridge.cash_after_obligations+ end++ # A paycheck window is still measured against its own paycheck: cash on hand+ # belongs to the gap before payday, not to the money that arrives on it.+ test "a paycheck window stays measured against its income" do+ set_cash(100_000)+ create_series(name: "Paycheck", amount: -100, due: Date.current + 1, preset: "weekly", income: true)+ create_series(name: "Rent", amount: 4_000, due: Date.current + 2)++ paying = Planner.new(@family, user: @user).plan(periods_limit: 3).reject(&:bridge?).first++ assert paying.short?, "a bill that outgrows its paycheck is short however much cash exists"+ end+++ # One unconvertible account used to fold to zero inside the sum, so the cash+ # figure quietly shrank and the bridge cried short against a partial balance.+ test "one unconvertible account makes the cash balance unknown, not smaller" do+ ExchangeRate.delete_all+ set_cash(5_000)+ @family.accounts.create!(name: "EUR pocket", balance: 100, currency: "EUR",+ accountable: Depository.new)+ create_series(name: "Paycheck", amount: -1840, due: Date.current + 5, preset: "weekly", income: true)+ create_series(name: "Water", amount: 64, due: Date.current + 2)++ bridge = Planner.new(@family, user: @user).plan(periods_limit: 3).first++ assert_nil bridge.cash_on_hand, "a partial balance is not a balance"+ assert_not bridge.short?, "an unknown balance is not evidence of a shortfall"+ end++ private+ # The family fixture carries more than one deposit account, and the plan+ # sums all of them, so a test that means to pin the cash has to set them all.+ def set_cash(amount)+ @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)+ series = @family.recurring_transactions.create!(+ name: name,+ account: @account,+ amount: amount,+ currency: "USD",+ bill_type: income ? "income" : "bill",+ expected_day_of_month: due.day,+ anchor_date: due,+ last_occurrence_date: due,+ next_expected_date: due,+ status: "active",+ manual: true+ )++ if preset != "monthly"+ RecurringTransaction::FrequencyPreset.apply(series, preset: preset, weekday: due.wday)+ series.save!+ end++ series+ end+enddiff --git a/test/models/recurring_transaction/pipeline_test.rb b/test/models/recurring_transaction/pipeline_test.rbnew file mode 100644index 0000000000..8cdc6d0472--- /dev/null+++ b/test/models/recurring_transaction/pipeline_test.rb@@ -0,0 +1,123 @@+require "test_helper"++class RecurringTransaction::PipelineTest < ActiveSupport::TestCase+ Pipeline = RecurringTransaction::Pipeline++ def setup+ @family = families(:dylan_family)+ @account = accounts(:depository)+ @family.recurring_transactions.destroy_all+ end++ test "run! detects, materializes and matches in one pass" do+ travel_to Date.new(2026, 8, 10) do+ # Three consistent monthly charges: enough for the identifier.+ 3.times do |i|+ create_entry(amount: 42.50, date: Date.new(2026, 8, 9) - i.months, name: "CITY POWER")+ end++ patterns_count = Pipeline.new(@family).run!++ assert_operator patterns_count, :>=, 1++ series = @family.recurring_transactions.find_by(name: "CITY POWER")+ assert series.present?, "detection must create the series"+ assert series.suggested?, "unclaimed detections land as suggestions"+ # Suggested series are not active, so nothing materializes until the+ # user confirms -- the pipeline must not conjure occurrences for them.+ assert_equal 0, series.recurring_occurrences.count+ end+ end++ test "run! with backfill reconstructs history and is idempotent" do+ travel_to Date.new(2026, 8, 10) do+ series = create_series(name: "CITY WATER", amount: 80, day_offset: -1)+ 3.times do |i|+ create_entry(amount: 80, date: Date.new(2026, 8, 9) - (i + 1).months, name: "CITY WATER")+ end++ # The upgraded-instance shape: series exist, occurrences never+ # materialized (creation auto-generates, so wipe them).+ RecurringOccurrence.where(recurring_transaction: series).delete_all+ assert @family.recurring_occurrences.none?++ Pipeline.new(@family).run!(backfill: true)++ historical = series.recurring_occurrences.where("due_on < ?", Date.new(2026, 8, 1))+ assert_operator historical.paid.count, :>=, 1,+ "the backfill reconstructs paid history from real entries"++ # Backfilling again reconstructs nothing twice.+ before_ids = series.recurring_occurrences.order(:id).pluck(:id)+ Pipeline.new(@family).run!(backfill: true)+ assert_equal before_ids, series.recurring_occurrences.order(:id).pluck(:id)+ end+ end++ test "run! without backfill never reconstructs history" do+ travel_to Date.new(2026, 8, 10) do+ series = create_series(name: "CITY GAS", amount: 55, day_offset: -1)+ create_entry(amount: 55, date: Date.new(2026, 6, 9), name: "CITY GAS")++ # Even in the upgraded-instance shape (zero occurrences), a plain run+ # must not backfill: background syncs keep their old cost profile.+ RecurringOccurrence.where(recurring_transaction: series).delete_all+ assert @family.recurring_occurrences.none?++ Pipeline.new(@family).run!++ assert_equal 0,+ series.recurring_occurrences.where("due_on < ?", Date.new(2026, 7, 1)).count,+ "only an explicit backfill request reconstructs history"+ end+ end++ test "run_with_lock! refuses to stack on a held family lock" do+ key = Pipeline.advisory_lock_key(@family.id)+ # Transactional tests hand every checkout the same shared fixture+ # connection, and a session can always re-take its own advisory lock, so+ # holding the lock needs a genuinely separate PG session.+ config = ActiveRecord::Base.connection_pool.db_config.configuration_hash+ other = PG.connect({+ dbname: config[:database], host: config[:host], port: config[:port],+ user: config[:username], password: config[:password]+ }.compact)+ other.exec("SELECT pg_advisory_lock(#{key})")++ result = Pipeline.new(@family).run_with_lock!++ assert_nil result, "a held lock reports nil rather than running"+ ensure+ other&.close+ end++ private++ def create_series(amount:, day_offset:, name: nil, merchant: nil)+ due = Date.current + day_offset++ @family.recurring_transactions.create!(+ name: name,+ merchant: merchant,+ account: @account,+ amount: amount,+ currency: "USD",+ expected_day_of_month: due.day,+ anchor_date: due,+ last_occurrence_date: due,+ next_expected_date: due,+ status: "active",+ manual: true+ )+ end++ def create_entry(amount:, date:, name:)+ @account.entries.create!(+ date: date,+ amount: amount,+ currency: "USD",+ name: name,+ entryable: Transaction.new+ )+ end+enddiff --git a/test/models/recurring_transaction/price_change_detector_test.rb b/test/models/recurring_transaction/price_change_detector_test.rbnew file mode 100644index 0000000000..a5097378e5--- /dev/null+++ b/test/models/recurring_transaction/price_change_detector_test.rb@@ -0,0 +1,131 @@+require "test_helper"++class RecurringTransaction::PriceChangeDetectorTest < ActiveSupport::TestCase+ Detector = RecurringTransaction::PriceChangeDetector++ def setup+ @family = families(:dylan_family)+ @account = accounts(:depository)+ @family.recurring_transactions.destroy_all+ @detector = Detector.new(@family)+ end++ test "two consecutive settlements at a new price update an auto series and record the change" do+ series = create_series(amount: 79.99, manual: false)+ settle(series, 1.month.ago.to_date, 94.99)+ settle(series, Date.current, 94.99)++ assert_equal 1, @detector.detect!++ series.reload+ assert_equal 94.99, series.amount+ change = series.recurring_price_changes.sole+ assert_equal 79.99, change.previous_amount+ assert_equal 94.99, change.new_amount+ assert change.recorded_by_detected?+ end++ test "a manual series gets the change recorded but keeps its declared amount" do+ series = create_series(amount: 100, manual: true)+ settle(series, 1.month.ago.to_date, 118)+ settle(series, Date.current, 118)++ @detector.detect!++ series.reload+ assert_equal 100, series.amount, "the user declared it; the user changes it"+ assert_equal 1, series.recurring_price_changes.count+ end++ test "one odd charge is never a price change" do+ series = create_series(amount: 79.99, manual: false)+ settle(series, 1.month.ago.to_date, 79.99)+ settle(series, Date.current, 94.99)++ assert_equal 0, @detector.detect!+ assert_empty series.recurring_price_changes+ end++ test "a pile of partial payments says nothing about price" do+ series = create_series(amount: 2000, manual: true)+ [ 1.month.ago.to_date, Date.current ].each do |due|+ occurrence = series.recurring_occurrences.create!(+ family: @family, original_due_on: due, due_on: due, currency: "USD"+ )+ allocator = RecurringTransaction::Allocator.new(occurrence)+ allocator.allocate!(amount: "1100")+ allocator.allocate!(amount: "1100")+ end++ assert_equal 0, @detector.detect!+ end++ test "detection does not repeat itself" do+ series = create_series(amount: 79.99, manual: false)+ settle(series, 1.month.ago.to_date, 94.99)+ settle(series, Date.current, 94.99)++ assert_equal 1, @detector.detect!+ assert_equal 0, @detector.detect!, "same evidence must not mint a second change"+ end++ test "the recorded change links the settling payment's entry, not a bystander suggestion" do+ series = create_series(amount: 79.99, manual: false)+ settle(series, 1.month.ago.to_date, 94.99)++ newest = series.recurring_occurrences.find_or_create_by!(+ family: @family, original_due_on: Date.current+ ) { |o| o.due_on = Date.current; o.currency = "USD" }+ decoy = @account.entries.create!(+ date: Date.current, amount: 94.99, currency: "USD",+ name: "FIBER INTERNET PENDING", entryable: Transaction.new+ )+ paying_entry = @account.entries.create!(+ date: Date.current, amount: 94.99, currency: "USD",+ name: "FIBER INTERNET", entryable: Transaction.new+ )+ # A suggestion sits on the same occurrence; reading the unordered+ # association's first row could hand the change the decoy's entry.+ RecurringTransaction::Allocator.new(newest).allocate_matched!(+ entry: decoy, state: "suggested", confidence: 0.7, signals: { name: 0.35 }+ )+ RecurringTransaction::Allocator.new(newest.reload).allocate!(entry: paying_entry, amount: "94.99")+ newest.reload+ RecurringTransaction::Allocator.new(newest).mark_paid! unless newest.paid?++ assert_equal 1, @detector.detect!++ change = series.recurring_price_changes.sole+ assert_equal paying_entry.id, change.entry_id,+ "the entry on the change must be the confirmed settlement's"+ end++ private+ def create_series(amount:, manual:)+ due = Date.current + 20++ @family.recurring_transactions.create!(+ name: "FIBER INTERNET",+ account: @account,+ amount: amount,+ currency: "USD",+ expected_day_of_month: due.day,+ anchor_date: due,+ last_occurrence_date: due,+ next_expected_date: due,+ status: "active",+ manual: manual+ )+ end++ def settle(series, due, paid_amount)+ occurrence = series.recurring_occurrences.find_or_create_by!(+ family: @family, original_due_on: due+ ) { |o| o.due_on = due; o.currency = "USD" }++ RecurringTransaction::Allocator.new(occurrence).allocate!(amount: paid_amount.to_s)+ occurrence.reload+ RecurringTransaction::Allocator.new(occurrence).mark_paid! unless occurrence.paid?+ occurrence.reload+ end+enddiff --git a/test/models/recurring_transaction/schedule_test.rb b/test/models/recurring_transaction/schedule_test.rbnew file mode 100644index 0000000000..81d0595916--- /dev/null+++ b/test/models/recurring_transaction/schedule_test.rb@@ -0,0 +1,517 @@+require "test_helper"++# Characterization tests for the recurring-transaction date math as it behaves+# today, written BEFORE extracting RecurringTransaction::Schedule. The extraction+# must keep every one of these green without edits; that is the proof of zero+# behavior change. Quirks are asserted deliberately (and called out inline) so a+# later, intentional fix has to change a test to do it.+class RecurringTransaction::ScheduleTest < ActiveSupport::TestCase+ def setup+ @family = families(:dylan_family)+ @merchant = merchants(:netflix)+ @account = accounts(:depository)+ end++ # --- RecurringTransaction.calculate_next_expected_date_from_today ---++ test "from_today returns this month's date when the expected day is still ahead" do+ travel_to Date.new(2026, 8, 13) do+ assert_equal Date.new(2026, 8, 20), RecurringTransaction.calculate_next_expected_date_from_today(20)+ end+ end++ test "from_today rolls to next month when the expected day is today" do+ travel_to Date.new(2026, 8, 13) do+ assert_equal Date.new(2026, 9, 13), RecurringTransaction.calculate_next_expected_date_from_today(13)+ end+ end++ test "from_today rolls to next month when the expected day has passed" do+ travel_to Date.new(2026, 8, 13) do+ assert_equal Date.new(2026, 9, 5), RecurringTransaction.calculate_next_expected_date_from_today(5)+ end+ end++ test "from_today handles a day absent from the current month by skipping to next month's real day" do+ # Quirk: on Feb 10 a day-31 bill does not clamp to Feb 28 -- Date.new raises,+ # and the rescue path lands on March 31. February is skipped entirely.+ travel_to Date.new(2026, 2, 10) do+ assert_equal Date.new(2026, 3, 31), RecurringTransaction.calculate_next_expected_date_from_today(31)+ end+ end++ # --- RecurringTransaction.calculate_next_expected_date_for ---++ test "for clamps to end of month when the day does not exist" do+ assert_equal Date.new(2026, 2, 28), RecurringTransaction.calculate_next_expected_date_for(Date.new(2026, 1, 31), 31)+ end++ test "for clamps to Feb 29 in a leap year" do+ assert_equal Date.new(2024, 2, 29), RecurringTransaction.calculate_next_expected_date_for(Date.new(2024, 1, 15), 31)+ end++ test "for lands on the expected day in the month after from_date" do+ assert_equal Date.new(2026, 9, 15), RecurringTransaction.calculate_next_expected_date_for(Date.new(2026, 8, 10), 15)+ end++ # --- RecurringTransaction#calculate_next_expected_date ---++ test "instance next date always jumps to the month after the last occurrence" do+ # Quirk (the early-payer bug): rent due on the 29th, last paid Aug 6, reads+ # as due Sep 29 -- the Aug 29 occurrence still ahead is skipped. Kept as-is+ # here; the write-path fix lands with the occurrence work.+ recurring = build_recurring(expected_day_of_month: 29, last_occurrence_date: Date.new(2026, 8, 6))+ assert_equal Date.new(2026, 9, 29), recurring.calculate_next_expected_date+ end++ test "instance next date defaults to counting from last_occurrence_date" do+ recurring = build_recurring(expected_day_of_month: 15, last_occurrence_date: Date.new(2026, 7, 15))+ assert_equal Date.new(2026, 8, 15), recurring.calculate_next_expected_date+ assert_equal Date.new(2026, 10, 15), recurring.calculate_next_expected_date(Date.new(2026, 9, 20))+ end++ test "instance next date clamps to end of month" do+ recurring = build_recurring(expected_day_of_month: 31, last_occurrence_date: Date.new(2026, 1, 15))+ assert_equal Date.new(2026, 2, 28), recurring.calculate_next_expected_date+ end++ # --- Identifier's private copy stays behavior-identical until it delegates ---++ test "identifier next date matches the model's math" do+ identifier = RecurringTransaction::Identifier.new(@family)+ assert_equal Date.new(2026, 2, 28), identifier.send(:calculate_next_expected_date, Date.new(2026, 1, 15), 31)+ assert_equal Date.new(2026, 9, 29), identifier.send(:calculate_next_expected_date, Date.new(2026, 8, 6), 29)+ end++ # --- day_of_month_scope: linear window, no wraparound, no clamping ---++ test "matching window is circular: a month-end entry matches a day-1 bill" do+ # A bill on the 1st paid a day or two early posts at the END of the prior+ # month. The window wraps the calendar circle, matching the Identifier's+ # matcher; the pre-unification SQL window [1, 3] silently missed these.+ recurring = create_recurring(expected_day_of_month: 1)+ in_window = create_matching_entry(recurring, date: Date.new(2026, 7, 2))+ wrapped = create_matching_entry(recurring, date: Date.new(2026, 7, 30))+ outside = create_matching_entry(recurring, date: Date.new(2026, 7, 27))++ matches = recurring.matching_transactions+ assert_includes matches, in_window+ assert_includes matches, wrapped+ assert_not_includes matches, outside+ end++ test "matching window for day 31 keeps its two-day reach" do+ recurring = create_recurring(expected_day_of_month: 31)+ in_window = create_matching_entry(recurring, date: Date.new(2026, 7, 29))+ outside = create_matching_entry(recurring, date: Date.new(2026, 7, 28))++ matches = recurring.matching_transactions+ assert_includes matches, in_window+ assert_not_includes matches, outside+ end++ test "matching window clamps the expected day into short months" do+ # A day-31 bill in February is due on the 28th; an entry on the 27th is one+ # day off the clamped day and must match. Unclamped, it read as four days+ # from the 31st and was dropped.+ recurring = create_recurring(expected_day_of_month: 31)+ clamped = create_matching_entry(recurring, date: Date.new(2026, 2, 27))++ assert_includes recurring.matching_transactions, clamped+ end++ # --- Schedule's own surface (new in the extraction) ---++ test "occurrences_between returns each monthly occurrence in the range inclusively" do+ schedule = RecurringTransaction::Schedule.new(expected_day_of_month: 15)+ assert_equal [ Date.new(2026, 8, 15), Date.new(2026, 9, 15), Date.new(2026, 10, 15) ],+ schedule.occurrences_between(Date.new(2026, 8, 15), Date.new(2026, 10, 20))+ end++ test "occurrences_between skips a first occurrence before the range start" do+ schedule = RecurringTransaction::Schedule.new(expected_day_of_month: 5)+ assert_equal [ Date.new(2026, 9, 5) ],+ schedule.occurrences_between(Date.new(2026, 8, 20), Date.new(2026, 9, 30))+ end++ test "occurrences_between clamps through short months without losing the day" do+ schedule = RecurringTransaction::Schedule.new(expected_day_of_month: 31)+ assert_equal [ Date.new(2026, 1, 31), Date.new(2026, 2, 28), Date.new(2026, 3, 31) ],+ schedule.occurrences_between(Date.new(2026, 1, 1), Date.new(2026, 4, 15))+ end++ test "occurrences_between is empty for an inverted range" do+ schedule = RecurringTransaction::Schedule.new(expected_day_of_month: 15)+ assert_empty schedule.occurrences_between(Date.new(2026, 9, 1), Date.new(2026, 8, 1))+ end++ test "cycle_for brackets a date between its surrounding occurrences" do+ schedule = RecurringTransaction::Schedule.new(expected_day_of_month: 29)+ cycle = schedule.cycle_for(Date.new(2026, 8, 10))+ assert_equal Date.new(2026, 7, 29), cycle.begin+ assert_equal Date.new(2026, 8, 29), cycle.end+ assert cycle.exclude_end?++ on_day = schedule.cycle_for(Date.new(2026, 8, 29))+ assert_equal Date.new(2026, 8, 29), on_day.begin+ assert_equal Date.new(2026, 9, 29), on_day.end+ end++ test "matches_day on a weekly cadence follows the weekday, not the day of month" do+ schedule = build_schedule(rules: [ rule(frequency: "weekly", weekday: 5) ])++ # Fridays across a month boundary sit on wildly different days of month.+ assert schedule.matches_day?(Date.new(2026, 5, 29))+ assert schedule.matches_day?(Date.new(2026, 6, 5))+ assert schedule.matches_day?(Date.new(2026, 6, 19))+ assert_not schedule.matches_day?(Date.new(2026, 6, 18)), "a Thursday is not this bill's day"+ end++ test "matches_day on a weekly rule without a weekday falls back to the anchor's weekday" do+ schedule = build_schedule(+ rules: [ rule(frequency: "weekly", weekday: nil, interval: 2) ],+ anchor_date: Date.new(2026, 8, 7)+ )++ assert schedule.matches_day?(Date.new(2026, 8, 21)), "a Friday two weeks after the anchor"+ assert_not schedule.matches_day?(Date.new(2026, 8, 13))+ end++ test "matches_day on a biweekly cadence rejects the off week's weekday" do+ schedule = build_schedule(+ rules: [ rule(frequency: "weekly", weekday: 5, interval: 2) ],+ anchor_date: Date.new(2026, 8, 7)+ )++ assert schedule.matches_day?(Date.new(2026, 8, 7))+ assert schedule.matches_day?(Date.new(2026, 8, 21))+ assert_not schedule.matches_day?(Date.new(2026, 8, 14)),+ "the right weekday in the wrong week is not this bill's day"+ end++ test "matches_day on an every-N-months cadence rejects the off months" do+ schedule = build_schedule(+ rules: [ rule(frequency: "monthly", day_of_month: 15, interval: 3) ],+ anchor_date: Date.new(2026, 2, 15)+ )++ assert schedule.matches_day?(Date.new(2026, 5, 15))+ assert schedule.matches_day?(Date.new(2026, 5, 17)), "day drift inside the tolerance still matches"+ assert_not schedule.matches_day?(Date.new(2026, 4, 15)),+ "the right day of month in an off-cycle month is not this bill's day"+ end++ test "matches_day stops matching once the series has ended on a date" do+ schedule = build_schedule(+ rules: [ rule(frequency: "monthly", day_of_month: 15) ],+ end_mode: "on_date", end_on: Date.new(2026, 8, 15)+ )++ assert schedule.matches_day?(Date.new(2026, 7, 15)), "history inside the window still matches"+ assert schedule.matches_day?(Date.new(2026, 8, 15)), "the final occurrence still matches"+ assert_not schedule.matches_day?(Date.new(2026, 9, 15)),+ "a date after the series ended is not this bill's day"+ end++ test "matches_day stops matching after the occurrence count is exhausted" do+ schedule = build_schedule(+ rules: [ rule(frequency: "monthly", day_of_month: 15) ],+ anchor_date: Date.new(2026, 5, 15),+ end_mode: "after_count", end_after_count: 3+ )++ assert schedule.matches_day?(Date.new(2026, 5, 15)), "the first occurrence of the plan matches"+ assert schedule.matches_day?(Date.new(2026, 7, 15)), "the third and final occurrence matches"+ assert_not schedule.matches_day?(Date.new(2026, 8, 15)),+ "a fourth occurrence never exists under a three-payment plan"+ end++ test "matches_day follows a weekend-adjusted occurrence to the day it is due" do+ # Saturdays adjusted forward land on Monday, two days off the raw weekday,+ # which the exact weekly match would otherwise reject.+ schedule = build_schedule(+ rules: [ rule(frequency: "weekly", weekday: 6) ],+ weekend_adjust: "after"+ )++ # Aug 15 2026 is a Saturday, so the payment is due Monday Aug 17.+ assert schedule.matches_day?(Date.new(2026, 8, 17)), "the Monday the bill is actually due"+ assert schedule.matches_day?(Date.new(2026, 8, 15)), "the raw scheduled Saturday still matches"+ assert_not schedule.matches_day?(Date.new(2026, 8, 18)), "a Tuesday is neither scheduled nor due"+ end++ test "matches_day does not match an occurrence the weekend skip removed" do+ schedule = build_schedule(+ rules: [ rule(frequency: "monthly", day_of_month: 15) ],+ weekend_adjust: "skip"+ )++ # Aug 15 2026 is a Saturday, so skip drops that month's occurrence entirely.+ assert_not schedule.matches_day?(Date.new(2026, 8, 15)),+ "a skipped occurrence does not exist, so its day matches nothing"+ assert schedule.matches_day?(Date.new(2026, 9, 15)), "a weekday occurrence is unaffected by skip"+ end++ # --- Rules-based engine ---++ test "weekly rule fires every week on its weekday" do+ schedule = build_schedule(rules: [ rule(frequency: "weekly", weekday: 5) ])+ # Fridays in August 2026: 7, 14, 21, 28+ assert_equal [ 7, 14, 21, 28 ].map { |d| Date.new(2026, 8, d) },+ schedule.occurrences_between(Date.new(2026, 8, 1), Date.new(2026, 8, 31))+ end++ test "weekly rule without a weekday generates on the anchor's weekday" do+ schedule = build_schedule(+ rules: [ rule(frequency: "weekly", weekday: nil) ],+ anchor_date: Date.new(2026, 8, 7)+ )+ # Fridays, inherited from the Friday anchor — same fallback matches_day? uses.+ assert_equal [ 7, 14, 21, 28 ].map { |d| Date.new(2026, 8, d) },+ schedule.occurrences_between(Date.new(2026, 8, 1), Date.new(2026, 8, 31))+ end++ test "weekly rule with neither weekday nor anchor cannot generate occurrences" do+ schedule = build_schedule(rules: [ rule(frequency: "weekly", weekday: nil) ])+ assert_raises(ArgumentError) do+ schedule.occurrences_between(Date.new(2026, 8, 1), Date.new(2026, 8, 31))+ end+ end++ test "biweekly rule keeps the anchor's phase, backward and forward" do+ schedule = build_schedule(+ rules: [ rule(frequency: "weekly", weekday: 5, interval: 2) ],+ anchor_date: Date.new(2026, 8, 7)+ )+ assert_equal [ Date.new(2026, 7, 24), Date.new(2026, 8, 7), Date.new(2026, 8, 21), Date.new(2026, 9, 4) ],+ schedule.occurrences_between(Date.new(2026, 7, 20), Date.new(2026, 9, 10))+ end++ test "semimonthly is two monthly rules" do+ schedule = build_schedule(rules: [+ rule(frequency: "monthly", day_of_month: 1),+ rule(frequency: "monthly", day_of_month: 15)+ ])+ assert_equal [ Date.new(2026, 8, 1), Date.new(2026, 8, 15), Date.new(2026, 9, 1), Date.new(2026, 9, 15) ],+ schedule.occurrences_between(Date.new(2026, 8, 1), Date.new(2026, 9, 20))+ end++ test "day_of_month -1 means the last day of every month" do+ schedule = build_schedule(rules: [ rule(frequency: "monthly", day_of_month: -1) ])+ assert_equal [ Date.new(2026, 1, 31), Date.new(2026, 2, 28), Date.new(2026, 3, 31) ],+ schedule.occurrences_between(Date.new(2026, 1, 1), Date.new(2026, 4, 1))+ end++ test "nth weekday rule finds the third friday" do+ schedule = build_schedule(rules: [ rule(frequency: "monthly", weekday: 5, weekday_ordinal: 3) ])+ assert_equal [ Date.new(2026, 8, 21), Date.new(2026, 9, 18) ],+ schedule.occurrences_between(Date.new(2026, 8, 1), Date.new(2026, 9, 30))+ end++ test "fifth weekday months are skipped when the month has no fifth" do+ schedule = build_schedule(rules: [ rule(frequency: "monthly", weekday: 1, weekday_ordinal: 5) ])+ # August 2026 has five Mondays (31st); September has only four.+ assert_equal [ Date.new(2026, 8, 31) ],+ schedule.occurrences_between(Date.new(2026, 8, 1), Date.new(2026, 9, 30))+ end++ test "ordinal -1 is the last weekday of the month" do+ schedule = build_schedule(rules: [ rule(frequency: "monthly", weekday: 5, weekday_ordinal: -1) ])+ assert_equal [ Date.new(2026, 8, 28), Date.new(2026, 9, 25) ],+ schedule.occurrences_between(Date.new(2026, 8, 1), Date.new(2026, 9, 30))+ end++ test "quarterly keeps the anchor's month phase" do+ schedule = build_schedule(+ rules: [ rule(frequency: "monthly", day_of_month: 15, interval: 3) ],+ anchor_date: Date.new(2026, 2, 15)+ )+ assert_equal [ Date.new(2026, 2, 15), Date.new(2026, 5, 15), Date.new(2026, 8, 15) ],+ schedule.occurrences_between(Date.new(2026, 1, 1), Date.new(2026, 9, 30))+ end++ test "yearly rule clamps Feb 29 outside leap years" do+ schedule = build_schedule(rules: [ rule(frequency: "yearly", month_of_year: 2, day_of_month: 29) ])+ assert_equal [ Date.new(2024, 2, 29), Date.new(2025, 2, 28), Date.new(2026, 2, 28) ],+ schedule.occurrences_between(Date.new(2024, 1, 1), Date.new(2026, 12, 31))+ end++ test "weekend adjust before moves saturday and sunday to friday" do+ # Aug 15 2026 is a Saturday, Sep 15 a Tuesday.+ schedule = build_schedule(rules: [ rule(frequency: "monthly", day_of_month: 15) ], weekend_adjust: "before")+ assert_equal [ Date.new(2026, 8, 14), Date.new(2026, 9, 15) ],+ schedule.occurrences_between(Date.new(2026, 8, 1), Date.new(2026, 9, 30))+ end++ test "weekend adjust after moves to monday and skip drops the occurrence" do+ after_schedule = build_schedule(rules: [ rule(frequency: "monthly", day_of_month: 15) ], weekend_adjust: "after")+ assert_equal [ Date.new(2026, 8, 17), Date.new(2026, 9, 15) ],+ after_schedule.occurrences_between(Date.new(2026, 8, 1), Date.new(2026, 9, 30))++ skip_schedule = build_schedule(rules: [ rule(frequency: "monthly", day_of_month: 15) ], weekend_adjust: "skip")+ assert_equal [ Date.new(2026, 9, 15) ],+ skip_schedule.occurrences_between(Date.new(2026, 8, 1), Date.new(2026, 9, 30))+ end++ test "weekend adjustment near the window edge cannot lose an occurrence" do+ # Due Sat Aug 1 2026, adjusted back to Fri Jul 31: a July-only query finds+ # it, an August-only query does not.+ schedule = build_schedule(rules: [ rule(frequency: "monthly", day_of_month: 1) ], weekend_adjust: "before")+ assert_includes schedule.occurrences_between(Date.new(2026, 7, 1), Date.new(2026, 7, 31)), Date.new(2026, 7, 31)+ assert_not_includes schedule.occurrences_between(Date.new(2026, 8, 1), Date.new(2026, 8, 31)), Date.new(2026, 7, 31)+ end++ test "end_on truncates the series" do+ schedule = build_schedule(+ rules: [ rule(frequency: "monthly", day_of_month: 15) ],+ end_mode: "on_date", end_on: Date.new(2026, 9, 30)+ )+ assert_equal [ Date.new(2026, 8, 15), Date.new(2026, 9, 15) ],+ schedule.occurrences_between(Date.new(2026, 8, 1), Date.new(2026, 12, 31))+ assert_nil schedule.first_occurrence_after(Date.new(2026, 9, 15))+ end++ test "after_count caps lifetime occurrences from the anchor" do+ schedule = build_schedule(+ rules: [ rule(frequency: "monthly", day_of_month: 15) ],+ anchor_date: Date.new(2026, 8, 15),+ end_mode: "after_count", end_after_count: 3+ )+ assert_equal [ Date.new(2026, 8, 15), Date.new(2026, 9, 15), Date.new(2026, 10, 15) ],+ schedule.occurrences_between(Date.new(2026, 1, 1), Date.new(2027, 12, 31))+ assert_equal Date.new(2026, 10, 15), schedule.first_occurrence_after(Date.new(2026, 9, 15))+ assert_nil schedule.first_occurrence_after(Date.new(2026, 10, 15))+ end++ test "a future-anchored after_count plan stays out of windows that end before it" do+ schedule = build_schedule(+ rules: [ rule(frequency: "monthly", day_of_month: 15) ],+ anchor_date: Date.new(2026, 10, 15),+ end_mode: "after_count", end_after_count: 3+ )+ assert_equal [], schedule.occurrences_between(Date.new(2026, 8, 1), Date.new(2026, 9, 30)),+ "the anchor occurrence is beyond the window and must not leak into it"+ assert_equal [ Date.new(2026, 10, 15) ],+ schedule.occurrences_between(Date.new(2026, 8, 1), Date.new(2026, 10, 31))+ end++ test "after_count counts an anchor occurrence adjusted before the anchor date" do+ # Aug 15 2026 is a Saturday, so "before" moves the first payment to+ # Friday Aug 14 -- a day before the anchor. It is still the plan's first+ # occurrence; a three-payment plan must not materialize a November one.+ schedule = build_schedule(+ rules: [ rule(frequency: "monthly", day_of_month: 15) ],+ anchor_date: Date.new(2026, 8, 15),+ weekend_adjust: "before",+ end_mode: "after_count", end_after_count: 3+ )++ assert_equal [ Date.new(2026, 8, 14), Date.new(2026, 9, 15), Date.new(2026, 10, 15) ],+ schedule.occurrences_between(Date.new(2026, 1, 1), Date.new(2027, 12, 31))+ assert_nil schedule.first_occurrence_after(Date.new(2026, 10, 15)),+ "a fourth occurrence never exists under a three-payment plan"+ end++ test "first_occurrence_after survives long weekend-skip droughts" do+ # A yearly bill due on a Saturday with skip adjustment has no occurrence+ # that year at all; the search must roll to the next non-weekend year.+ schedule = build_schedule(+ rules: [ rule(frequency: "yearly", month_of_year: 8, day_of_month: 15) ],+ weekend_adjust: "skip"+ )+ # Aug 15: 2026 Saturday (skipped), 2027 Sunday (skipped), 2028 Tuesday.+ assert_equal Date.new(2028, 8, 15), schedule.first_occurrence_after(Date.new(2026, 1, 1))+ end++ test "occurrences_per_year sums rule cadences" do+ semimonthly = build_schedule(rules: [+ rule(frequency: "monthly", day_of_month: 1),+ rule(frequency: "monthly", day_of_month: 15)+ ])+ assert_in_delta 24.0, semimonthly.occurrences_per_year, 0.001++ biweekly = build_schedule(rules: [ rule(frequency: "weekly", weekday: 5, interval: 2) ],+ anchor_date: Date.new(2026, 8, 7))+ assert_in_delta 26.09, biweekly.occurrences_per_year, 0.01+ end++ test "legacy shims fall through to correct semantics for non-monthly shapes" do+ schedule = build_schedule(rules: [ rule(frequency: "weekly", weekday: 5) ])+ # Aug 13 2026 is a Thursday; the next Friday is the 14th -- no+ # jump-a-whole-period quirk for rule shapes the old code never handled.+ assert_equal Date.new(2026, 8, 14), schedule.next_occurrence_after(Date.new(2026, 8, 13))+ end++ test "interval rules refuse to build without an anchor" do+ assert_raises(ArgumentError) do+ build_schedule(rules: [ rule(frequency: "weekly", weekday: 5, interval: 2) ])+ end+ end++ test "cycle_for works across rule shapes" do+ schedule = build_schedule(rules: [+ rule(frequency: "monthly", day_of_month: 1),+ rule(frequency: "monthly", day_of_month: 15)+ ])+ cycle = schedule.cycle_for(Date.new(2026, 8, 10))+ assert_equal Date.new(2026, 8, 1), cycle.begin+ assert_equal Date.new(2026, 8, 15), cycle.end+ end+++ # The legacy shim builds Date.new from expected_day_of_month, and a nil there+ # raises TypeError past the ArgumentError rescue.+ test "a rules-backed schedule with no legacy day never enters the shim" do+ schedule = build_schedule(rules: [ rule(frequency: "monthly", day_of_month: 12) ])++ assert_nothing_raised do+ assert_equal 12, schedule.next_occurrence_from_today.day+ end+ end++ private+ def rule(frequency:, interval: 1, day_of_month: nil, weekday: nil, weekday_ordinal: nil, month_of_year: nil)+ RecurringTransaction::Schedule::Rule.new(+ frequency:, interval:, day_of_month:, weekday:, weekday_ordinal:, month_of_year:+ )+ end++ def build_schedule(rules:, anchor_date: nil, weekend_adjust: "none", end_mode: "never", end_on: nil, end_after_count: nil)+ RecurringTransaction::Schedule.new(+ expected_day_of_month: nil,+ rules:, anchor_date:, weekend_adjust:, end_mode:, end_on:, end_after_count:+ )+ end++ def build_recurring(**overrides)+ @family.recurring_transactions.build(+ account: @account,+ merchant: @merchant,+ amount: 29.99,+ currency: "USD",+ expected_day_of_month: 15,+ last_occurrence_date: Date.new(2026, 7, 15),+ next_expected_date: Date.new(2026, 8, 15),+ status: "active",+ **overrides+ )+ end++ def create_recurring(**overrides)+ # Name-keyed with a unique name: identity no longer includes amount, so+ # reusing the fixture's merchant would collide with netflix_subscription.+ recurring = build_recurring(merchant: nil, name: "Window test bill #{overrides[:expected_day_of_month]}", **overrides)+ recurring.save!+ recurring+ end++ def create_matching_entry(recurring, date:)+ @account.entries.create!(+ date: date,+ amount: recurring.amount,+ currency: recurring.currency,+ name: recurring.name || "Netflix charge",+ entryable: Transaction.new(merchant_id: recurring.merchant_id)+ )+ end+enddiff --git a/test/models/recurring_transaction_amount_edit_test.rb b/test/models/recurring_transaction_amount_edit_test.rbnew file mode 100644index 0000000000..ceffa05ffb--- /dev/null+++ b/test/models/recurring_transaction_amount_edit_test.rb@@ -0,0 +1,75 @@+require "test_helper"++# A price change means "it costs this much from now on". These pin that, because+# occurrences resolve their amount from the series live, so the natural+# behaviour is the wrong one: raising the rent restates last month's unpaid rent.+class RecurringTransactionAmountEditTest < ActiveSupport::TestCase+ setup do+ @family = users(:family_admin).family+ @series = @family.recurring_transactions.new(+ account: accounts(:depository), name: "Rent", amount: 1200, dedup_scope: "amt-edit",+ currency: "USD", expected_day_of_month: 1,+ last_occurrence_date: 2.months.ago.to_date.beginning_of_month,+ next_expected_date: Date.current.beginning_of_month,+ status: "active", manual: false)+ RecurringTransaction::FrequencyPreset.apply(@series, preset: "monthly", day_of_month: 1)+ @series.save!+ RecurringTransaction::OccurrenceGenerator.new(@series).generate!++ rows = @series.recurring_occurrences.order(:due_on).to_a+ @already_due = rows.first+ @upcoming = rows.find { |o| o.due_on > Date.current }+ assert @already_due.due_on <= Date.current, "premise: first row is already due"+ assert @upcoming.present?, "premise: at least one future row"+ end++ test "a price rise leaves what is already due alone and applies to future dates" do+ assert_equal 1200, @already_due.resolved_expected_amount.to_i+ assert_equal 1200, @upcoming.resolved_expected_amount.to_i++ @series.update!(amount: 1300)+ [ @already_due, @upcoming ].each(&:reload)++ assert_equal 1200, @already_due.resolved_expected_amount.to_i,+ "an occurrence the user was already shown as owed must not be restated"+ assert_equal 1300, @upcoming.resolved_expected_amount.to_i,+ "future dates should cost the new amount"+ end++ test "the pin is stored, so a second edit cannot walk it forward" do+ @series.update!(amount: 1300)+ @series.update!(amount: 1400)+ @already_due.reload++ assert_equal 1200, @already_due.expected_amount.to_i+ assert_equal 1200, @already_due.resolved_expected_amount.to_i+ end++ test "a price drop pins the same way" do+ @series.update!(amount: 900)+ [ @already_due, @upcoming ].each(&:reload)++ assert_equal 1200, @already_due.resolved_expected_amount.to_i+ assert_equal 900, @upcoming.resolved_expected_amount.to_i+ end++ test "editing something other than the amount pins nothing" do+ @series.update!(notes: "moved to autopay")+ @already_due.reload++ assert_nil @already_due.expected_amount,+ "only a price change should freeze an occurrence's amount"+ end++ test "an occurrence carrying a payment keeps the amount the allocator froze" do+ entry = accounts(:depository).entries.create!(name: "part", date: @already_due.due_on,+ amount: 300, currency: "USD", entryable: Transaction.new)+ RecurringTransaction::Allocator.new(@already_due).allocate!(entry: entry, amount: 300)+ @already_due.reload+ assert_equal 1200, @already_due.expected_amount.to_i, "premise: allocator froze it"++ @series.update!(amount: 1300)+ @already_due.reload+ assert_equal 1200, @already_due.resolved_expected_amount.to_i+ end+enddiff --git a/test/models/recurring_transaction_test.rb b/test/models/recurring_transaction_test.rbindex 4b94222183..113d979e0b 100644--- a/test/models/recurring_transaction_test.rb+++ b/test/models/recurring_transaction_test.rb@@ -9,6 +9,21 @@ class RecurringTransactionTest < ActiveSupport::TestCase@family.recurring_transactions.destroy_allend+ test "payable ignores a debt destination that belongs to another family" do+ foreign_card = families(:empty).accounts.create!(+ name: "Foreign Card", balance: 0, currency: "USD", accountable: CreditCard.new+ )+ transfer = @family.recurring_transactions.create!(+ name: "Card payment", account: @account, amount: 200, currency: "USD",+ expected_day_of_month: 5, last_occurrence_date: Date.current,+ next_expected_date: 1.month.from_now.to_date, status: "active", manual: true+ )+ transfer.update_column(:destination_account_id, foreign_card.id)++ assert_not_includes @family.recurring_transactions.payable, transfer,+ "a destination outside the family is not this family's obligation"+ end+test "status is required" dorecurring = @family.recurring_transactions.build(account: @account,@@ -25,6 +40,43 @@ class RecurringTransactionTest < ActiveSupport::TestCaseassert_includes recurring.errors[:status], "can't be blank"end+ # end_after_count is a permitted parameter and the generator materialises a+ # finite plan whole, so an absurd value is not a silly setting: it is one+ # request deciding how far the table grows. 100,000 wrote 100,000 rows.+ test "an absurd installment plan length is refused before any row is written" do+ plan = build_recurring(bill_type: "installment", end_mode: "after_count",+ end_after_count: 100_000)++ assert_not plan.valid?+ assert_includes plan.errors.attribute_names, :end_after_count+ end++ test "a realistic installment plan length is accepted" do+ plan = build_recurring(bill_type: "installment", end_mode: "after_count",+ end_after_count: 24, anchor_date: Date.current)++ assert plan.valid?, plan.errors.full_messages.to_sentence+ end++ # category_id is permitted too, and nothing checked whose category it was.+ test "a category belonging to another family is refused" do+ other = Family.create!(name: "Other Household", currency: "USD")+ foreign = Category.create!(family: other, name: "Their Groceries", color: "#ff0000")++ bill = build_recurring(category_id: foreign.id)++ assert_not bill.valid?+ assert_includes bill.errors.attribute_names, :category_id+ end++ test "a category belonging to this family is accepted" do+ own = Category.create!(family: @family, name: "Our Groceries", color: "#00ff00")++ bill = build_recurring(category_id: own.id)++ assert bill.valid?, bill.errors.full_messages.to_sentence+ end+test "occurrence count cannot be negative" dorecurring = @family.recurring_transactions.build(account: @account,@@ -68,7 +120,7 @@ class RecurringTransactionTest < ActiveSupport::TestCaseassert_equal @account, recurring.accountassert_equal 15.99, recurring.amountassert_equal "USD", recurring.currency- assert_equal "active", recurring.status+ assert_equal "suggested", recurring.statusassert_equal 3, recurring.occurrence_countend@@ -205,7 +257,7 @@ class RecurringTransactionTest < ActiveSupport::TestCaseassert_equal(-1000.00, recurring.amount)assert recurring.amount.negative?, "Income should have negative amount"assert_equal "USD", recurring.currency- assert_equal "active", recurring.status+ assert_equal "suggested", recurring.statusendtest "identify_patterns_for creates name-based recurring transactions for transactions without merchants" do@@ -233,7 +285,7 @@ class RecurringTransactionTest < ActiveSupport::TestCaseassert_equal "Local Coffee Shop", recurring.nameassert_equal 25.00, recurring.amountassert_equal "USD", recurring.currency- assert_equal "active", recurring.status+ assert_equal "suggested", recurring.statusassert_equal 3, recurring.occurrence_countend@@ -305,6 +357,36 @@ class RecurringTransactionTest < ActiveSupport::TestCaseassert matches.all? { |entry| entry.name == "Gym Membership" }end+ test "matching_transactions rejects a same-day charge in an off-cycle month" do+ recurring = build_recurring(+ merchant: nil,+ name: "Quarterly water bill",+ amount: 90.00,+ anchor_date: Date.new(2026, 5, 15),+ last_occurrence_date: Date.new(2026, 5, 15),+ next_expected_date: Date.new(2026, 8, 15)+ )+ recurring.save!+ recurring.recurrence_rules.create!(frequency: "monthly", interval: 3, day_of_month: 15)++ entries = [ Date.new(2026, 8, 15), Date.new(2026, 7, 15) ].map do |date|+ @account.entries.create!(+ date: date,+ amount: 90.00,+ currency: "USD",+ name: "Quarterly water bill",+ entryable: Transaction.create!+ )+ end+ on_cycle, off_cycle = entries++ matches = recurring.matching_transactions.map(&:id)+ # Positive control: the on-cycle month's charge still matches.+ assert_includes matches, on_cycle.id+ # Same calendar day, off-cycle month: the day window alone would accept it.+ assert_not_includes matches, off_cycle.id+ end+test "validation requires either merchant or name" dorecurring = @family.recurring_transactions.build(account: @account,@@ -487,6 +569,53 @@ class RecurringTransactionTest < ActiveSupport::TestCaseassert_equal 1, recurring.occurrence_countend+ test "create_from_transaction collides on an identical series and still forks a different price tier" do+ first_transaction = Transaction.create!(merchant: @merchant, category: categories(:food_and_drink))+ @account.entries.create!(+ date: 2.months.ago,+ amount: 50.00,+ currency: "USD",+ name: "Test Transaction",+ entryable: first_transaction+ )++ recurring = RecurringTransaction.create_from_transaction(first_transaction)+ assert_equal "50.0", recurring.dedup_scope, "the amount is stamped before the first insert"++ # An identical series (same identity, same amount) must hit the unique+ # index on the first insert, not slip past it as a stamped duplicate.+ duplicate_transaction = Transaction.create!(merchant: @merchant, category: categories(:food_and_drink))+ @account.entries.create!(+ date: 1.month.ago,+ amount: 50.00,+ currency: "USD",+ name: "Test Transaction",+ entryable: duplicate_transaction+ )++ assert_no_difference "@family.recurring_transactions.count" do+ assert_raises ActiveRecord::RecordNotUnique do+ RecurringTransaction.create_from_transaction(duplicate_transaction)+ end+ end++ # A different amount is a legitimate second tier from the same biller and+ # still forks a sibling series.+ tier_transaction = Transaction.create!(merchant: @merchant, category: categories(:food_and_drink))+ @account.entries.create!(+ date: 1.month.ago,+ amount: 80.00,+ currency: "USD",+ name: "Test Transaction",+ entryable: tier_transaction+ )++ assert_difference "@family.recurring_transactions.count", 1 do+ tier = RecurringTransaction.create_from_transaction(tier_transaction)+ assert_equal "80.0", tier.dedup_scope+ end+ end+test "amount_within_variance_band? allows up to 2x and excludes beyond" doassert RecurringTransaction.amount_within_variance_band?(199, 100)assert_not RecurringTransaction.amount_within_variance_band?(201, 100)@@ -559,11 +688,14 @@ class RecurringTransactionTest < ActiveSupport::TestCasemanual: true)- # Auto recurring - 2 months threshold with different amount to avoid unique constraint+ # Auto recurring - 2 months threshold. A second series on the same+ # identity carries a dedup_scope discriminator now that amount is no+ # longer part of the unique indexes.auto_recurring = @family.recurring_transactions.create!(account: @account,merchant: @merchant,amount: 60.00,+ dedup_scope: "60.0",currency: "USD",expected_day_of_month: 15,last_occurrence_date: 3.months.ago,@@ -933,6 +1065,40 @@ class RecurringTransactionTest < ActiveSupport::TestCaseassert_includes rt.errors[:destination_account], "must belong to the same family as the source account"end+ test "validation rejects a source account from a different family" do+ other_family = Family.create!(name: "Other", locale: "en", date_format: "%Y-%m-%d", currency: "USD")+ other_account = other_family.accounts.create!(name: "Other depository", balance: 0, currency: "USD", accountable: Depository.new)++ rt = build_recurring(account: other_account)++ assert_not rt.valid?+ assert_includes rt.errors[:account], "must belong to this family"+ end++ test "validation rejects a transfer whose endpoints both sit in another family" do+ # The endpoint pair is internally consistent here, so only the check+ # against the bill's own family can catch it.+ other_family = Family.create!(name: "Other", locale: "en", date_format: "%Y-%m-%d", currency: "USD")+ other_source = other_family.accounts.create!(name: "Other depository", balance: 0, currency: "USD", accountable: Depository.new)+ other_destination = other_family.accounts.create!(name: "Other card", balance: 0, currency: "USD", accountable: CreditCard.new)++ rt = @family.recurring_transactions.build(+ account: other_source,+ destination_account: other_destination,+ name: "Foreign transfer pair",+ amount: 100,+ currency: "USD",+ expected_day_of_month: 1,+ last_occurrence_date: Date.current,+ next_expected_date: 1.month.from_now.to_date,+ manual: true+ )++ assert_not rt.valid?+ assert_includes rt.errors[:account], "must belong to this family"+ assert_includes rt.errors[:destination_account], "must belong to this family"+ end+test "create_from_transfer builds a recurring transfer with both endpoints" dosource = @accountdestination = accounts(:credit_card)@@ -1201,4 +1367,175 @@ class RecurringTransactionTest < ActiveSupport::TestCase@family.recurring_transactions.create!(base_attrs)endend++ # The scheme allowlist is the security boundary for payment_url: the value is+ # rendered as a link, so a "javascript:" or "data:" scheme surviving to the view+ # would be stored XSS. These cases are the contract, not incidental coverage.+ test "payment_url rejects any scheme other than http and https" do+ [+ "javascript:alert(1)",+ "JaVaScRiPt:alert(1)",+ " javascript:alert(1) ",+ "data:text/html,<script>alert(1)</script>",+ "mailto:[email protected]",+ "ftp://example.com/pay",+ "https://"+ ].each do |hostile|+ recurring = build_recurring(payment_url: hostile)++ assert_not recurring.valid?, "expected #{hostile.inspect} to be rejected"+ assert_includes recurring.errors.attribute_names, :payment_url+ end+ end++ test "payment_url accepts http and https and promotes a bare host to https" do+ {+ "https://pay.example.com/bill" => "https://pay.example.com/bill",+ "http://pay.example.com" => "http://pay.example.com",+ "pay.example.com" => "https://pay.example.com",+ " pay.example.com " => "https://pay.example.com",+ # A colon followed by digits is a port, not a scheme. Self-hosters link to+ # LAN services this way.+ "192.168.1.5:3000/pay" => "https://192.168.1.5:3000/pay"+ }.each do |input, expected|+ recurring = build_recurring(payment_url: input)++ assert recurring.valid?, "expected #{input.inspect} to be accepted: #{recurring.errors.full_messages}"+ assert_equal expected, recurring.payment_url+ end+ end++ test "payment_url is optional and normalizes blank to nil" do+ [ nil, "", " " ].each do |blank|+ recurring = build_recurring(payment_url: blank)++ assert recurring.valid?+ assert_nil recurring.payment_url+ end+ end++ # `calculate_next_expected_date` jumps to `last_occurrence_date.next_month`, so a+ # payment posting earlier in the month than the expected day skips the occurrence+ # still ahead this month: rent due on the 29th, last paid on the 6th, is stored as+ # due next month. Bills must not repeat that to the user.+ test "next_due_date corrects a stored date that skipped this month's occurrence" do+ travel_to Date.new(2026, 8, 13) do+ recurring = build_recurring(+ expected_day_of_month: 29,+ last_occurrence_date: Date.new(2026, 8, 6),+ next_expected_date: Date.new(2026, 9, 29)+ )++ assert_equal Date.new(2026, 8, 29), recurring.next_due_date+ assert_not recurring.overdue?+ end+ end++ test "next_due_date leaves a correct stored date alone" do+ travel_to Date.new(2026, 8, 13) do+ recurring = build_recurring(+ expected_day_of_month: 21,+ last_occurrence_date: Date.new(2026, 7, 21),+ next_expected_date: Date.new(2026, 8, 21)+ )++ assert_equal Date.new(2026, 8, 21), recurring.next_due_date+ end+ end++ test "next_due_date does not advance an overdue bill past its due date" do+ travel_to Date.new(2026, 8, 13) do+ recurring = build_recurring(+ expected_day_of_month: 5,+ last_occurrence_date: Date.new(2026, 7, 5),+ next_expected_date: Date.new(2026, 8, 5)+ )++ assert_equal Date.new(2026, 8, 5), recurring.next_due_date+ assert recurring.overdue?+ end+ end++ test "bills scope keeps expenses and drops income, transfers and paused rows" do+ expense = build_recurring(name: "Rent", merchant: nil, amount: 1200).tap(&:save!)+ build_recurring(name: "Paycheck", merchant: nil, amount: -2000).tap(&:save!)+ build_recurring(name: "Paused", merchant: nil, amount: 40, status: "inactive").tap(&:save!)+ build_recurring(name: "Card payment", merchant: nil, amount: 500,+ destination_account: accounts(:credit_card)).tap(&:save!)++ assert_equal [ expense.id ], @family.recurring_transactions.bills.pluck(:id)+ end++ test "display_name prefers the merchant over the free-text name" do+ assert_equal @merchant.name, build_recurring(merchant: @merchant, name: nil).display_name+ assert_equal "Rent", build_recurring(merchant: nil, name: "Rent").display_name+ end+++ # next_expected_date only advances when a bank entry matches during sync, so+ # a bill settled through mark_paid!, a manual payment or the assistant froze+ # it in the past forever. next_due_date returned it verbatim, which reported+ # a fully paid bill as long overdue and answered due_within_days for a date+ # 45 days gone.+ test "a settled bill looks ahead to its next open cycle, not at a stale hint" do+ series = stale_hint_series++ series.recurring_occurrences.where("due_on <= ?", Date.current).find_each do |occurrence|+ RecurringTransaction::Allocator.new(occurrence).mark_paid!+ end+ series.reload++ assert_operator series.next_due_date, :>, Date.current,+ "every owed cycle is paid, so nothing is due in the past"+ assert_not series.overdue?+ assert_equal 0, series.cycles_overdue+ end++ test "an unpaid past cycle is still overdue" do+ series = stale_hint_series++ assert series.overdue?, "the oldest unpaid cycle is what makes a bill late"+ assert_equal series.recurring_occurrences.open_status.minimum(:due_on), series.next_due_date+ end++ # "Whole cycles" is meant literally. The old formula added one, so a bill a+ # single day late already claimed a full cycle missed.+ test "cycles_overdue counts only whole cycles elapsed" do+ series = stale_hint_series+ due = Date.current - 1+ series.recurring_occurrences.destroy_all+ series.recurring_occurrences.create!(+ family: @family, original_due_on: due, due_on: due,+ currency: "USD", expected_amount: 60, status: "scheduled"+ )++ assert series.reload.overdue?+ assert_equal 0, series.cycles_overdue, "one day late is not one cycle missed"+ end++ private++ def stale_hint_series+ stale = 45.days.ago.to_date+ series = @family.recurring_transactions.create!(+ name: "Gym #{stale}", account: accounts(:depository), amount: 60,+ currency: "USD", status: "active", bill_type: "subscription", manual: true,+ dedup_scope: "gym-#{stale}", expected_day_of_month: stale.day,+ last_occurrence_date: stale << 1, next_expected_date: stale+ )+ series.reload+ end++ def build_recurring(**overrides)+ @family.recurring_transactions.build({+ account: @account,+ merchant: @merchant,+ amount: 29.99,+ currency: "USD",+ expected_day_of_month: 15,+ last_occurrence_date: Date.current,+ next_expected_date: 1.month.from_now.to_date,+ status: "active"+ }.merge(overrides))+ endend