Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat: match recurring bills by bank transaction note reference (#4895)

Chris Werner Rau2db9f5b25ca1
diff --git a/app/controllers/bills_controller.rb b/app/controllers/bills_controller.rb
index 3a2af43c5c..8646299ec1 100644
--- a/app/controllers/bills_controller.rb
+++ b/app/controllers/bills_controller.rb
@@ -640,9 +640,9 @@ class BillsController < ApplicationController
end
# Only occurrences the overview lists: open rows and this month's paid ones.
- # Ending a bill leaves its scheduled occurrences behind and the matcher
- # still scores them, and skipping closes an occurrence but keeps its
- # suggestion, so neither may ask about a row the page doesn't show.
+ # Ending a bill leaves its scheduled occurrences and any earlier suggestion on
+ # them, and skipping closes an occurrence but keeps its suggestion, so neither
+ # may ask about a row the page doesn't show.
def suggested_allocations(listed)
RecurringAllocation
.suggested
diff --git a/app/controllers/recurring_occurrences_controller.rb b/app/controllers/recurring_occurrences_controller.rb
index 5ee6802d34..3d32525897 100644
--- a/app/controllers/recurring_occurrences_controller.rb
+++ b/app/controllers/recurring_occurrences_controller.rb
@@ -142,31 +142,42 @@ class RecurringOccurrencesController < ApplicationController
series = @occurrence.recurring_transaction
matcher = RecurringTransaction::Matcher.new(Current.family)
- scope = candidate_scope
- .where(date: candidate_window)
+ # preload, not includes: entryable is polymorphic so it can never be
+ # joined, and naming it keeps the raw transactions join above out of
+ # Rails' eager-load machinery.
+ eligible = candidate_scope
.not_excluded_or_split_parent
.where.not(id: RecurringMatchRejection.where(recurring_transaction: series).select(:entry_id))
- # preload, not includes: entryable is polymorphic so it can never be
- # joined, and naming it keeps the raw transactions join above out of
- # Rails' eager-load machinery.
.preload(:entryable)
- .limit(RANKED_SCAN_LIMIT)
+ scope = eligible.where(date: candidate_window).limit(RANKED_SCAN_LIMIT)
- scope = if series.merchant_id.present?
+ identity_scope = if series.merchant_id.present?
scope.where(transactions: { merchant_id: series.merchant_id })
else
patterns = matcher_name_patterns(series)
- return [] if patterns.empty?
-
- scope.where("entries.name ILIKE ANY (ARRAY[?])", patterns)
+ patterns.empty? ? scope.none : scope.where("entries.name ILIKE ANY (ARRAY[?])", patterns)
end
- scored = scope.filter_map do |entry|
+ entries = (identity_scope.to_a + reference_candidates(series, eligible)).uniq(&:id)
+ scored = entries.filter_map do |entry|
explanation = matcher.explain(@occurrence, entry)
[ entry, explanation ] if explanation
end
- scored.sort_by { |_entry, explanation| -explanation.confidence }.first(RANKED_SHOWN)
+ # A reference match leads, as it does in the matcher, then confidence.
+ scored.sort_by { |_entry, explanation| [ explanation.signals.key?(:reference) ? 0 : 1, -explanation.confidence ] }.first(RANKED_SHOWN)
+ end
+
+ # Payments whose note carries the bill's bank reference match whatever their
+ # name or date, so the ranked list offers them too.
+ def reference_candidates(series, eligible)
+ needle = series.bank_reference && RecurringTransaction::Matcher.normalize_name(series.bank_reference)
+ return [] if needle.blank? || needle.length < RecurringTransaction::Matcher::MIN_REFERENCE_LENGTH
+
+ pattern = "%#{ActiveRecord::Base.sanitize_sql_like(needle).gsub(/\s+/, '%')}%"
+ nearest_first = Arel.sql(ActiveRecord::Base.sanitize_sql_array([ "ABS(entries.date - ?) ASC", @occurrence.due_on ]))
+ scope = eligible.where("entries.date <= ?", Date.current).order(nearest_first).limit(RANKED_SCAN_LIMIT)
+ RecurringTransaction::Matcher.with_note_patterns(scope, [ pattern ]).to_a
end
# The names the matcher itself would recognize: the series' own name plus
@@ -188,7 +199,7 @@ class RecurringOccurrencesController < ApplicationController
# payment being hunted for is usually the one the window already excluded.
def candidate_entries
scope = if @candidate_query.present?
- candidate_scope.where("entries.name ILIKE :q", q: "%#{ActiveRecord::Base.sanitize_sql_like(@candidate_query)}%")
+ candidate_scope.where("entries.name ILIKE :q OR entries.notes ILIKE :q", q: "%#{ActiveRecord::Base.sanitize_sql_like(@candidate_query)}%")
else
candidate_scope.where(date: candidate_window)
end
diff --git a/app/controllers/recurring_transactions_controller.rb b/app/controllers/recurring_transactions_controller.rb
index 4ec2fead7e..43ad35bcd5 100644
--- a/app/controllers/recurring_transactions_controller.rb
+++ b/app/controllers/recurring_transactions_controller.rb
@@ -393,7 +393,7 @@ class RecurringTransactionsController < ApplicationController
# raw permit.
def recurring_transaction_params
params.require(:recurring_transaction).permit(
- :payment_url, :autopay, :notes, :bill_type, :category_id,
+ :payment_url, :autopay, :notes, :bank_reference, :reference_only, :bill_type, :category_id,
:renews_on, :trial_ends_on, :cancelled_on, :end_after_count,
:frequency_preset, :frequency_day_of_month, :frequency_second_day_of_month,
:frequency_weekday, :frequency_month_of_year, :frequency_interval, :frequency_interval_unit,
@@ -405,7 +405,7 @@ class RecurringTransactionsController < ApplicationController
params.require(:recurring_transaction).permit(
:name, :amount, :currency, :account_id, :first_due_on, :frequency_preset,
:frequency_interval, :frequency_interval_unit,
- :payment_url, :autopay, :notes, :is_income, :category_id
+ :payment_url, :autopay, :notes, :bank_reference, :reference_only, :is_income, :category_id
)
end
diff --git a/app/helpers/bills_helper.rb b/app/helpers/bills_helper.rb
index e789cd07e2..6cedede3d7 100644
--- a/app/helpers/bills_helper.rb
+++ b/app/helpers/bills_helper.rb
@@ -100,6 +100,8 @@ module BillsHelper
{
aliases: Array(series.matcher_hints["name_aliases"]).compact_blank,
learned_pct: series.learned_amount_tolerance_pct.to_f,
+ reference: series.matcher_hints["bank_reference"].presence,
+ reference_only: series.matcher_hints["bank_reference"].present? && series.matcher_hints["reference_only"] == true,
detected_name: series.merchant_id.blank? ? series.matcher_hints["detected_name"].presence : nil
}
end
@@ -128,9 +130,9 @@ module BillsHelper
def entry_bill_allocations(entry)
return [] unless preview_features_enabled?
- entry.recurring_allocations
- .includes(recurring_occurrence: :recurring_transaction)
- .reject { |allocation| allocation.recurring_occurrence.nil? }
+ RecurringTransaction::Allocator.active_allocations(entry.recurring_allocations)
+ .includes(recurring_occurrence: :recurring_transaction)
+ .to_a
end
# The paycheck split into `[key, percent]` pairs; the caller owns the colours.
@@ -459,6 +461,7 @@ module BillsHelper
reasons << t("bills.match.same_merchant") if signals[:merchant]
reasons << t("bills.match.name_matches") if signals[:name]
reasons << t("bills.match.same_transfer") if signals[:transfer]
+ reasons << t("bills.match.reference", reference: signals[:reference]) if signals[:reference].is_a?(String)
# Guarded: the review queue can hold an allocation whose entry has been
# nullified out from under it, so neither figure is guaranteed.
diff --git a/app/models/assistant/function/bills_support.rb b/app/models/assistant/function/bills_support.rb
index e95e510b75..87cd75f250 100644
--- a/app/models/assistant/function/bills_support.rb
+++ b/app/models/assistant/function/bills_support.rb
@@ -17,6 +17,15 @@ module Assistant::Function::BillsSupport
"ended" => %w[ended]
}.freeze
+ BANK_REFERENCE_DESCRIPTION = "A stable token from the bank's payment note (Verwendungszweck) for this bill, " \
+ "e.g. a contract or customer number. A payment on the bill's account whose note " \
+ "contains it matches this bill, whatever the amount or date, unless the bill is bound " \
+ "to a merchant and the payment carries a different one. Needs an account; not for " \
+ "income. Use something distinctive, at least 3 characters."
+
+ REFERENCE_ONLY_DESCRIPTION = "With a bank_reference set: match payments by that reference alone and ignore " \
+ "the bill's name and merchant. Default false; has no effect without a reference."
+
private
def recurring_disabled?
family.recurring_transactions_disabled?
@@ -92,7 +101,9 @@ module Assistant::Function::BillsSupport
account: account_ref(series.account),
destination_account: account_ref(series.destination_account),
monthly_equivalent: series.monthly_equivalent_amount&.abs&.format,
- payment_url: series.payment_url
+ payment_url: series.payment_url,
+ bank_reference: series.bank_reference,
+ reference_only: series.reference_only?
}.compact
end
diff --git a/app/models/assistant/function/create_bill.rb b/app/models/assistant/function/create_bill.rb
index 47dc43063b..4a12e5c5c4 100644
--- a/app/models/assistant/function/create_bill.rb
+++ b/app/models/assistant/function/create_bill.rb
@@ -51,7 +51,9 @@ class Assistant::Function::CreateBill < Assistant::Function
category_name: { type: "string", description: "Exact category name from get_categories." },
autopay: { type: "boolean" },
payment_url: { type: "string", description: "Where this bill gets paid." },
- notes: { type: "string" }
+ notes: { type: "string" },
+ bank_reference: { type: "string", description: BANK_REFERENCE_DESCRIPTION },
+ reference_only: { type: "boolean", description: REFERENCE_ONLY_DESCRIPTION }
}
)
end
@@ -86,7 +88,9 @@ class Assistant::Function::CreateBill < Assistant::Function
account_id: account&.id,
payment_url: params["payment_url"],
autopay: autopay,
- notes: params["notes"]
+ notes: params["notes"],
+ bank_reference: params["bank_reference"],
+ reference_only: params["reference_only"]
}
).build
diff --git a/app/models/assistant/function/update_bill.rb b/app/models/assistant/function/update_bill.rb
index 81b2b9400a..371ac2b53d 100644
--- a/app/models/assistant/function/update_bill.rb
+++ b/app/models/assistant/function/update_bill.rb
@@ -57,6 +57,8 @@ class Assistant::Function::UpdateBill < Assistant::Function
autopay: { type: "boolean" },
payment_url: { type: "string" },
notes: { type: "string" },
+ bank_reference: { type: "string", description: "#{BANK_REFERENCE_DESCRIPTION} Empty string clears it." },
+ reference_only: { type: "boolean", description: REFERENCE_ONLY_DESCRIPTION },
renews_on: { type: "string", description: "YYYY-MM-DD" },
trial_ends_on: { type: "string", description: "YYYY-MM-DD" }
}
@@ -94,7 +96,7 @@ class Assistant::Function::UpdateBill < Assistant::Function
private
def apply_simple_fields(series, params, changed)
{ "name" => :name, "autopay" => :autopay, "payment_url" => :payment_url,
- "notes" => :notes, "renews_on" => :renews_on, "trial_ends_on" => :trial_ends_on }.each do |key, attribute|
+ "notes" => :notes, "bank_reference" => :bank_reference, "reference_only" => :reference_only, "renews_on" => :renews_on, "trial_ends_on" => :trial_ends_on }.each do |key, attribute|
next unless params.key?(key)
value = params[key]
diff --git a/app/models/recurring_transaction.rb b/app/models/recurring_transaction.rb
index d91889a794..81aca2df1d 100644
--- a/app/models/recurring_transaction.rb
+++ b/app/models/recurring_transaction.rb
@@ -55,6 +55,7 @@ class RecurringTransaction < ApplicationRecord
validate :amount_variance_consistency
validate :transfer_endpoints_consistent
validate :payment_url_is_http
+ validate :bank_reference_is_distinctive
validate :anchor_required_for_intervals
validate :end_mode_fields_consistent
validate :bill_type_matches_shape
@@ -161,6 +162,55 @@ class RecurringTransaction < ApplicationRecord
matcher_hints.to_h["detected_name"].presence || name
end
+ # The stable token a bank puts in this series' payment notes (a contract or
+ # customer number, a transfer's Verwendungszweck), kept in matcher_hints so
+ # the matcher can recognise variable-amount payments by it. User-entered;
+ # see Matcher::REFERENCE_BONUS for what it can and cannot do.
+ def bank_reference
+ matcher_hints.to_h["bank_reference"].presence
+ end
+
+ def bank_reference=(value)
+ cleaned = value.to_s.squish
+ hints = matcher_hints.to_h.except("bank_reference")
+ hints["bank_reference"] = cleaned if cleaned.present?
+ self.matcher_hints = hints
+ end
+
+
+ # "Match by reference only": the bank reference is then the bill's whole
+ # identity for the matcher (see Matcher#reference_only?). Meaningless
+ # without a reference, so it reads false then.
+ def reference_only?
+ bank_reference.present? && reference_effective? && matcher_hints.to_h["reference_only"] == true
+ end
+
+ # Whether the text carries this bill's bank reference, ignoring case and
+ # whitespace the way the matcher does.
+ def note_carries_reference?(text)
+ return false if bank_reference.blank? || text.blank?
+
+ needle = Matcher.normalize_name(bank_reference)
+ needle.length >= Matcher::MIN_REFERENCE_LENGTH && Matcher.normalize_name(text).include?(needle)
+ end
+
+ # A reference only ever matches payments on this bill's account, and never
+ # income (see Matcher#matched_reference).
+ def reference_effective?
+ account_id.present? && !typed_income?
+ end
+
+ # The stored switch as the form shows it, effective or not.
+ def reference_only
+ matcher_hints.to_h["reference_only"] == true
+ end
+
+ def reference_only=(value)
+ hints = matcher_hints.to_h.except("reference_only")
+ hints["reference_only"] = true if ActiveModel::Type::Boolean.new.cast(value)
+ self.matcher_hints = hints
+ end
+
# A bill first renamed without a stored detected name keeps its original name, so the detector can still claim it.
def preserve_detected_name
self.matcher_hints = matcher_hints.to_h.merge("detected_name" => name_was)
@@ -195,6 +245,15 @@ class RecurringTransaction < ApplicationRecord
end
end
+ def bank_reference_is_distinctive
+ return if bank_reference.blank?
+
+ errors.add(:bank_reference, :needs_account_and_expense) unless reference_effective?
+ min = RecurringTransaction::Matcher::MIN_REFERENCE_LENGTH
+ errors.add(:bank_reference, :too_short, count: min) if bank_reference.length < min
+ errors.add(:bank_reference, :too_long, count: 100) if bank_reference.length > 100
+ end
+
def payment_url_is_http
return if payment_url.blank?
@@ -656,6 +715,17 @@ class RecurringTransaction < ApplicationRecord
.where.not(id: RecurringMatchRejection.where(entry_id: entry.id).select(:recurring_transaction_id))
.order(:created_at)
.find do |series|
+ # A reference-only bill is identified by the note alone, whatever the
+ # amount, but never across signs: a refund is not its payment.
+ same_sign = series.amount.positive? == entry.amount.positive?
+ next same_sign && series.note_carries_reference?(entry.notes) if series.reference_only?
+
+ # Any bill's reference in the note identifies its payment too, unless
+ # the bill is bound to a different merchant than the payment's.
+ if same_sign && series.reference_effective? && series.note_carries_reference?(entry.notes) &&
+ !(series.merchant_id.present? && merchant&.id.present? && merchant.id != series.merchant_id)
+ next true
+ end
next false unless amount_within_variance_band?(entry.amount, series.amount)
if series.merchant_id.present?
diff --git a/app/models/recurring_transaction/allocator.rb b/app/models/recurring_transaction/allocator.rb
index 54504b271f..e396b1383d 100644
--- a/app/models/recurring_transaction/allocator.rb
+++ b/app/models/recurring_transaction/allocator.rb
@@ -158,7 +158,17 @@ class RecurringTransaction
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)
+ # A payment the series' bank reference identified is the bill's own
+ # whatever it amounted to, so it is recorded at what was really paid
+ # instead of being capped at what the cycle still needed.
+ whole_payment = signals.to_h.with_indifferent_access[:reference].present? && entry.currency == occurrence.currency
+
+ # A suggestion pins nothing, so a confirmed reference payment replaces any
+ # it already has (a leftover from an earlier run) rather than being blocked
+ # by the capacity it holds or by the unique index.
+ RecurringAllocation.where(entry_id: entry.id, state: "suggested").destroy_all if whole_payment && state == "confirmed"
+
+ allocated, source_amount, source_currency = resolve_amounts(nil, entry, reference: whole_payment)
return nil unless allocated.positive?
guard_entry_capacity!(entry, source_amount)
@@ -274,6 +284,10 @@ class RecurringTransaction
confirmed = occurrence.allocations.confirmed.to_a
return false if confirmed.empty?
+ # Identified by the series' bank reference: that is the cycle's payment
+ # whatever it amounted to, under- or overpaid.
+ return true if confirmed.any? { |allocation| allocation.match_signals.to_h["reference"].present? }
+
total = confirmed.sum(&:allocated_amount)
if confirmed.size == 1
@@ -284,7 +298,7 @@ class RecurringTransaction
total >= expected - RecurringOccurrence::CLOSE_EPSILON
end
- def resolve_amounts(amount, entry)
+ def resolve_amounts(amount, entry, reference: false)
if entry.nil?
raise ArgumentError, "an amount is required for a payment without a transaction" if amount.blank?
@@ -305,7 +319,7 @@ class RecurringTransaction
capacity = entry_capacity(entry, entry_total)
remaining = occurrence.remaining_amount
- if settles_bill?(entry, entry_total)
+ if settles_bill?(entry, entry_total, reference: reference)
capacity
else
remaining.positive? ? [ capacity, remaining ].min : capacity
@@ -346,8 +360,11 @@ class RecurringTransaction
# its real amount instead of being capped at the estimate. It qualifies
# only when nothing has been paid against this occurrence or this entry
# yet, and its amount sits inside the same tolerance band the matcher uses.
- # Partial payments and accumulations keep the capped behaviour.
- def settles_bill?(entry, entry_total)
+ # Partial payments and accumulations keep the capped behaviour. A payment
+ # the bill's own bank reference identified is the bill itself whatever it
+ # amounted to and however many payments the cycle already holds.
+ def settles_bill?(entry, entry_total, reference: false)
+ return true if reference
return false if occurrence.allocations.confirmed.exists?
return false if active_allocations_for(entry).exists?
diff --git a/app/models/recurring_transaction/declared_bill.rb b/app/models/recurring_transaction/declared_bill.rb
index 6b5f1bc292..a69058f253 100644
--- a/app/models/recurring_transaction/declared_bill.rb
+++ b/app/models/recurring_transaction/declared_bill.rb
@@ -49,6 +49,8 @@ class RecurringTransaction
payment_url: attrs[:payment_url],
autopay: ActiveModel::Type::Boolean.new.cast(attrs[:autopay]) || false,
notes: attrs[:notes],
+ bank_reference: (attrs[:bank_reference] unless is_income),
+ reference_only: (attrs[:reference_only] unless is_income),
status: "active",
manual: true,
occurrence_count: 0
diff --git a/app/models/recurring_transaction/identifier.rb b/app/models/recurring_transaction/identifier.rb
index 08ae533b1b..e305b18671 100644
--- a/app/models/recurring_transaction/identifier.rb
+++ b/app/models/recurring_transaction/identifier.rb
@@ -129,7 +129,9 @@ class RecurringTransaction
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?
+ # A reference-only series is tracked by its note alone, not by the
+ # name or merchant groups this pass refreshes it from.
+ next if claimed.manual? || claimed.ended? || claimed.reference_only?
update_claimed_series(claimed, pattern)
next
@@ -144,7 +146,7 @@ class RecurringTransaction
# 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?
+ next if racer.manual? || racer.ended? || racer.reference_only?
update_claimed_series(racer, pattern)
end
@@ -348,7 +350,7 @@ class RecurringTransaction
def preload_series_to_refresh(recurring_patterns, existing_by_identity)
to_refresh = recurring_patterns.filter_map do |pattern|
claimed = nearest_within_tolerance(existing_by_identity[pattern_identity(pattern)] || [], pattern[:expected_amount_avg])
- claimed unless claimed.nil? || claimed.manual? || claimed.ended?
+ claimed unless claimed.nil? || claimed.manual? || claimed.ended? || claimed.reference_only?
end.uniq
return if to_refresh.empty?
@@ -528,6 +530,8 @@ class RecurringTransaction
end
def manual_recurring_matches_entry?(recurring, entry)
+ # Identified by its note alone; the matcher tracks it, not name and day.
+ return false if recurring.reference_only?
return false unless entry.currency == recurring.currency
return false if recurring.account_id.present? && entry.account_id != recurring.account_id
# Anchor on the row's stable, user-set seed amount (not
diff --git a/app/models/recurring_transaction/matcher.rb b/app/models/recurring_transaction/matcher.rb
index ad3f257e92..7da30b078f 100644
--- a/app/models/recurring_transaction/matcher.rb
+++ b/app/models/recurring_transaction/matcher.rb
@@ -20,10 +20,52 @@ class RecurringTransaction
# Learned tolerance never widens beyond this, whatever the user confirms.
MAX_LEARNED_TOLERANCE_PCT = 25
- Candidate = Data.define(:occurrence, :entry, :confidence, :signals)
+ # A series' bank reference (the stable token in the payment note, e.g. a
+ # contract number) found in an entry's note is a hard match: whatever the
+ # amount, the entry belongs to the series, scores at least the exact tier
+ # and beats every non-reference candidate for the same entry (see
+ # Candidate#reference_matched? and #unambiguous?). Notes are written by
+ # third parties, so this is bounded by the filters that stay: account, sign
+ # and currency, never a transfer leg or another merchant's charge, a user's
+ # rejection, an entry already confirmed to another bill, and never income or
+ # an account-less series. The accepted trade-off is that a forged note on the
+ # same account links a same-sign payment of any amount and date, so a
+ # reference should be distinctive.
+ REFERENCE_BONUS = BigDecimal("0.25")
+
+ # A reference match ignores the date window and pairs with the nearest
+ # occurrence by due date, open or paid, past or future, however far. Two
+ # limits keep that bounded: a live run only looks at reference payments of
+ # the last REFERENCE_LOOKBACK_DAYS (and at settled cycles up to one cadence
+ # older than that, so the nearest cycle is loaded), and a payment more than
+ # one cycle before the series' first cycle is left alone rather than attached
+ # to a cycle that has nothing to do with it.
+ REFERENCE_LOOKBACK_DAYS = 90
+ MAX_CYCLE_DAYS = 366
+
+ # Shorter references are too likely to appear in unrelated notes by chance.
+ MIN_REFERENCE_LENGTH = 3
+
+ Candidate = Data.define(:occurrence, :entry, :confidence, :signals) do
+ def reference_matched?
+ signals[:reference].present?
+ end
+ end
attr_reader :family
+ # Narrows an entries scope (joined to transactions) to those whose own note,
+ # or for a transfer outflow its receiving leg's note, matches any of the
+ # LIKE patterns, case-insensitively. A coarse prefilter: matched_reference
+ # makes the exact call.
+ def self.with_note_patterns(scope, patterns)
+ own = Entry.arel_table[:notes].matches_any(patterns)
+ inflow = Transfer.joins(inflow_transaction: :entry)
+ .where(Entry.arel_table[:notes].matches_any(patterns))
+ .select(:outflow_transaction_id)
+ scope.where(own.or(Transaction.arel_table[:id].in(inflow.arel)))
+ end
+
def self.normalize_name(name)
name.to_s.downcase.gsub(/\s+/, " ").strip
end
@@ -34,13 +76,19 @@ class RecurringTransaction
# Live mode: exact tier auto-links, high tier lands in the review queue.
def run!
- apply(collect_candidates, suggest: true)
+ reconcile_reference_allocations!
+ written = apply(collect_candidates, suggest: true)
+ close_reference_settled!
+ written
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)
+ reconcile_reference_allocations!
+ written = apply(collect_candidates(include_closed_window: true), suggest: false)
+ close_reference_settled!
+ written
end
# Re-attaches allocations whose entry was replaced under them: some
@@ -97,37 +145,210 @@ class RecurringTransaction
def explain(occurrence, entry)
series = occurrence.recurring_transaction
return nil unless identity_matches?(series, entry)
- return nil unless within_window?(occurrence, entry)
+ return nil unless within_window?(occurrence, entry) || matched_reference(series, 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)
+ Explanation.new(confidence: [ confidence, 1 ].min, signals: signals)
end
private
+ # A confirmed allocation the matcher wrote itself is never reconsidered as
+ # a candidate, so allocations that predate a bill's reference are
+ # reconciled against it here, in one pass over what the matcher wrote:
+ #
+ # * A payment naming another active bill's reference on the same account,
+ # or lacking the reference of a reference-only bill, is released so the
+ # right bill can link it. Only a cycle still open or current is released;
+ # settled history of older cycles is left as it is.
+ # * A payment the bill's reference identified, sitting on another cycle than
+ # the one it belongs to, moves there (see target_cycle), one allocation per
+ # entry, with both cycles recomputing whether they are settled.
+ #
+ # Allocations a person created or confirmed are never touched. Only three
+ # kinds of allocation can need either step, and only those are loaded: on a
+ # reference-only bill, carrying a reference signal, or whose note names a
+ # bill's reference. A family without a bank reference skips the scan.
+ def reconcile_reference_allocations!
+ return unless reference_bills?
+
+ rehomes = []
+ reconcilable_allocations.find_each do |allocation|
+ series = allocation.recurring_occurrence.recurring_transaction
+ entry = allocation.entry
+ next unless series.active? && entry
+
+ current = allocation.recurring_occurrence
+ if contradicted_allocation?(series, entry)
+ Allocator.new(current).unallocate!(allocation) if releasable_cycle?(current, series)
+ elsif allocation.match_signals.to_h["reference"].present? && matched_reference(series, entry)
+ rehomes << [ allocation, series, entry ]
+ end
+ end
+
+ # Oldest payment first, each against the cycles as the moves before it
+ # left them, so a backlog fills in order instead of piling onto one cycle.
+ rehomes.sort_by { |_, _, entry| [ entry.date, entry.id ] }.each do |allocation, series, entry|
+ rehome_reference_allocation!(allocation, series, entry)
+ rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid
+ # The target cycle already holds this entry; leave the allocation where it is.
+ next
+ end
+ end
+
+ def reference_bills?
+ family.recurring_transactions.active.where.not("matcher_hints->>'bank_reference' IS NULL").exists?
+ end
+
+ # The confirmed allocations the matcher wrote that reconciliation can act
+ # on: those on a reference-only bill (contradicted unless the note carries
+ # the reference), those a reference identified (re-homed), and those whose
+ # note names some bill's reference (released from a bill it does not
+ # belong to). The note test is a coarse SQL prefilter; the exact decision
+ # stays in contradicted_allocation?.
+ def reconcilable_allocations
+ base = RecurringAllocation.confirmed
+ .where(source: "auto_matched")
+ .where.not(entry_id: nil)
+ .joins(recurring_occurrence: :recurring_transaction)
+ .where(recurring_occurrences: { family_id: family.id })
+
+ relevant = base.where("recurring_transactions.matcher_hints->>'reference_only' = 'true'")
+ .or(base.where("recurring_allocations.match_signals->>'reference' IS NOT NULL"))
+
+ needles = references_by_account.values.flatten(1).map(&:last).uniq
+ if needles.any?
+ noting_reference = self.class.with_note_patterns(
+ family.entries
+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id")
+ .where(entryable_type: "Transaction", account_id: references_by_account.keys),
+ like_patterns(needles)
+ )
+ relevant = relevant.or(base.where(entry_id: noting_reference.select(:id)))
+ end
+
+ relevant.preload(:entry, recurring_occurrence: :recurring_transaction)
+ end
+
+ def like_patterns(needles)
+ needles.map { |needle| "%#{Entry.sanitize_sql_like(needle).gsub(/\s+/, '%')}%" }
+ end
+
+ def rehome_reference_allocation!(allocation, series, entry)
+ current = allocation.recurring_occurrence
+ target = target_cycle(series, entry)
+ return if target.nil? || target.id == current.id
+ return unless rehome_target?(target, current, entry)
+
+ move_allocation!(allocation, current, target, entry)
+ end
+
+ def rehome_target?(target, current, entry)
+ if target.scheduled? && within_window?(target, entry)
+ target.effective_due_on < current.effective_due_on
+ else
+ cycle_distance(target, entry) < cycle_distance(current, entry)
+ end
+ end
+
+ # Open cycles and the one a person would call the current month's; anything
+ # older and settled is history.
+ def releasable_cycle?(occurrence, series)
+ occurrence.scheduled? || occurrence.effective_due_on > Date.current - cycle_days(series)
+ end
+
+ def cycle_days(series)
+ (365.25 / series.schedule.occurrences_per_year).floor
+ end
+
+ def contradicted_allocation?(series, entry)
+ if reference_only?(series)
+ !reference_only_identity?(series, entry)
+ else
+ matched_reference(series, entry).nil? && conflicting_reference?(series, entry)
+ end
+ end
+
+ # The move and both cycles' close state are one unit: occurrence row locks
+ # in a fixed order, then the entry lock, as every allocator write takes
+ # them. Suggestions the entry holds are dropped first, a confirmed payment
+ # replaces them.
+ def move_allocation!(allocation, from, to, entry)
+ RecurringAllocation.transaction do
+ [ from, to ].sort_by(&:id).each(&:lock!)
+ Allocator.lock_entry!(entry)
+ RecurringAllocation.where(entry_id: entry.id, state: "suggested").destroy_all
+ allocation.update!(recurring_occurrence_id: to.id)
+ [ from, to ].each { |occurrence| Allocator.new(occurrence.reload).refresh_close_state! }
+ end
+ end
+
+ # The reference decides which bill, not which month: of a bill's cycles the
+ # payment goes to the oldest open one whose window covers it, and only when
+ # none does, to the nearest by due date.
+ def target_cycle(series, entry)
+ pick_cycle(series.recurring_occurrences.reload.select { |occurrence| occurrence.scheduled? || occurrence.paid? }, entry)
+ end
+
+ # An open cycle a late payment can still be for: the entry is inside its
+ # window and less than a cycle past its due date, so a payment is never
+ # pulled back onto a month that went unpaid long before it.
+ def claimable_open?(occurrence, entry)
+ occurrence.scheduled? && within_window?(occurrence, entry) &&
+ (entry.date - occurrence.effective_due_on).to_i < cycle_days(occurrence.recurring_transaction)
+ end
+
+ def pick_cycle(cycles, entry)
+ open_in_window = cycles.select { |occurrence| claimable_open?(occurrence, entry) }
+ return open_in_window.min_by(&:effective_due_on) if open_in_window.any?
+
+ cycles.min_by { |occurrence| [ cycle_distance(occurrence, entry), occurrence.paid? ? 1 : 0 ] }
+ end
+
+ def cycle_distance(occurrence, entry)
+ (entry.date - occurrence.effective_due_on).to_i.abs
+ end
+
+ # Cycles whose payment the bank reference identified are settled whatever
+ # it amounted to (Allocator#close_worthy?), but that rule only runs when an
+ # allocation is written. Allocations linked before it existed, or a cycle
+ # reopened since, are closed here so a rerun reconciles them.
+ def close_reference_settled!
+ unsettled = RecurringAllocation.confirmed
+ .where.not("match_signals ->> 'reference' IS NULL")
+ .select(:recurring_occurrence_id)
+ family.recurring_occurrences.open_status.where(id: unsettled).find_each do |occurrence|
+ Allocator.new(occurrence).refresh_close_state!
+ end
+ end
+
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. A split child whose parent is also a candidate
- # waits until every other candidate had its turn: the parent claims its
- # bill as if the split came after matching, and the Allocator then
- # refuses the child. The id tiebreak only makes equally confident
+ # A split child whose parent is also a candidate waits until every other
+ # candidate had its turn: the parent claims its bill as if the split came
+ # after matching, and the Allocator then refuses the child. Otherwise
+ # reference matches claim first, then highest confidence; each entry is
+ # assigned at most once per run, and each occurrence once, except that
+ # reference matches may add further payments to an occurrence: the
+ # bill's own note on a second payment in one cycle makes it an extra
+ # payment, not a rival. The id tiebreak only makes equally confident
# candidates resolve deterministically, since sort_by is not stable.
- candidate_entry_ids = candidates.to_set { |candidate| candidate.entry.id }
- ordered = candidates.sort_by do |candidate|
+ pruned = prune_to_nearest_per_series(candidates)
+ candidate_entry_ids = pruned.to_set { |candidate| candidate.entry.id }
+ ordered = pruned.sort_by do |candidate|
parent_competes = candidate_entry_ids.include?(candidate.entry.parent_entry_id)
- [ parent_competes ? 1 : 0, -candidate.confidence, candidate.occurrence.id, candidate.entry.id ]
+ [ parent_competes ? 1 : 0, candidate.reference_matched? ? 0 : 1, -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)
+ next if !candidate.reference_matched? && taken_occurrences.include?(candidate.occurrence.id)
tier = tier_for(candidate, ordered)
next if tier.nil?
@@ -167,7 +388,21 @@ class RecurringTransaction
other.entry.id == candidate.entry.id && other.occurrence.id != candidate.occurrence.id
end
- runner_up.nil? || candidate.confidence - runner_up.confidence >= AMBIGUITY_MARGIN
+ return true if runner_up.nil?
+ # A reference match is the entry's own series' payment; it only competes
+ # with other reference matches.
+ return candidate.reference_matched? if candidate.reference_matched? != runner_up.reference_matched?
+
+ # Two bills that both matched by the same reference are told apart by how
+ # well the payment fits each (amount, date, account), not by the points
+ # their identity path happened to give the reference.
+ return reference_fit(candidate) - reference_fit(runner_up) >= AMBIGUITY_MARGIN if candidate.reference_matched?
+
+ candidate.confidence - runner_up.confidence >= AMBIGUITY_MARGIN
+ end
+
+ def reference_fit(candidate)
+ candidate.signals.values_at(:amount, :date, :account).compact.sum.to_d
end
# False when the occurrence should stay open to the next candidate.
@@ -175,7 +410,9 @@ class RecurringTransaction
Allocator.new(candidate.occurrence).allocate_matched!(
entry: candidate.entry,
state: tier == :exact ? "confirmed" : "suggested",
- confidence: candidate.confidence,
+ # Reference bonuses can push the raw score past 1; the column is a
+ # probability.
+ confidence: [ candidate.confidence, 1 ].min,
signals: candidate.signals
)
true
@@ -196,12 +433,13 @@ class RecurringTransaction
# 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
+ occurrences = open_occurrences + paid_reference_occurrences(include_closed_window)
return [] if occurrences.empty?
rejected = rejected_pairs
allocated_entry_ids = confirmed_entry_ids
occurrences_by_series = occurrences.group_by(&:recurring_transaction_id)
+ earliest_due = occurrences_by_series.transform_values { |list| list.map(&:effective_due_on).min }
candidates = entries_for(occurrences, include_closed_window).flat_map do |entry|
next [] if allocated_entry_ids.include?(entry.id)
@@ -211,18 +449,25 @@ class RecurringTransaction
next [] if rejected.include?([ series_id, entry.id ])
next [] unless identity_matches?(series, entry)
+ # The bill's own reference on the payment pairs it with any cycle.
+ reference_hit = matched_reference(series, entry).present?
+ next [] if reference_hit && before_first_cycle?(series, entry, earliest_due[series_id])
+
series_occurrences.filter_map do |occurrence|
- next unless within_window?(occurrence, entry)
+ next unless reference_hit || within_window?(occurrence, entry)
confidence, signals = score(occurrence, series, entry)
next if confidence < HIGH_TIER
+ # A settled cycle only takes further payments the bill's own
+ # reference vouches for.
+ next if occurrence.paid? && signals[:reference].blank?
Candidate.new(occurrence: occurrence, entry: entry, confidence: confidence, signals: signals)
end
end
end
- prune_to_nearest_per_series(candidates)
+ candidates
end
# Within one series an entry pairs only with its nearest open occurrence.
@@ -231,18 +476,64 @@ class RecurringTransaction
# 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 } }
+ groups = candidates.group_by { |candidate| [ candidate.entry.id, candidate.occurrence.recurring_transaction_id ] }.values
+ reference_groups, plain_groups = groups.partition { |group| group.first.reference_matched? }
+
+ picks = plain_groups.map { |group| nearest_candidate(group) }
+
+ # A reference payment goes to the oldest open cycle whose window covers it:
+ # a late payment settles the overdue month, not the nearer next one. Oldest
+ # payment first, each cycle taking one, so a backlog fills in order instead
+ # of every payment claiming the oldest cycle; with no open cycle left in
+ # reach the payment goes to the nearest, as any other payment does.
+ claimed = Set.new
+ reference_groups.sort_by { |group| [ group.first.entry.date, group.first.entry.id ] }.each do |group|
+ open_in_window = group.select { |candidate| !claimed.include?(candidate.occurrence.id) && claimable_open?(candidate.occurrence, candidate.entry) }
+ pick = open_in_window.min_by { |candidate| candidate.occurrence.effective_due_on } || nearest_candidate(group)
+ claimed << pick.occurrence.id
+ picks << pick
+ end
+
+ picks
+ end
+
+ # Ties go to the occurrence still open.
+ def nearest_candidate(group)
+ group.min_by { |candidate| [ (candidate.entry.date - candidate.occurrence.effective_due_on).to_i.abs, candidate.occurrence.paid? ? 1 : 0 ] }
end
+ # Cycles of an ended series take no payments: such a series is usually the
+ # superseded twin of an active one and would only make every payment look
+ # ambiguous. Paused and inactive series keep theirs, so a late payment
+ # still reaches a paused bill's overdue leftover.
def open_occurrences
family.recurring_occurrences
.open_status
+ .joins(:recurring_transaction)
+ .where.not(recurring_transactions: { status: "ended" })
.includes(recurring_transaction: :recurrence_rules)
.to_a
end
+ # Settled cycles of bills that carry a bank reference stay candidates for
+ # further reference payments (a second payment in the same month). A live
+ # run only sees payments from the last REFERENCE_LOOKBACK_DAYS, so a cycle
+ # can only be the nearest one for them if it is at most one cadence older
+ # than that; backfill takes all history.
+ def paid_reference_occurrences(include_closed_window)
+ scope = family.recurring_occurrences
+ .paid
+ .joins(:recurring_transaction)
+ .merge(RecurringTransaction.active)
+ .where.not("recurring_transactions.matcher_hints->>'bank_reference' IS NULL")
+ .includes(recurring_transaction: :recurrence_rules)
+ return scope.to_a if include_closed_window
+
+ scope.where("recurring_occurrences.due_on >= ?", (REFERENCE_LOOKBACK_DAYS + MAX_CYCLE_DAYS).days.ago.to_date).select do |occurrence|
+ occurrence.due_on >= (REFERENCE_LOOKBACK_DAYS + cycle_days(occurrence.recurring_transaction)).days.ago.to_date
+ end
+ end
+
def rejected_pairs
RecurringMatchRejection
.joins(:recurring_transaction)
@@ -251,14 +542,16 @@ class RecurringTransaction
.to_set
end
+ # Confirmed payments that spoke for an entry. Allocations of an ended
+ # series (a deleted or dismissed bill) are tombstones the Allocator
+ # ignores too, so an active series can still take the entry.
+ def confirmed_allocations
+ Allocator.active_allocations(RecurringAllocation.confirmed.where.not(entry_id: nil))
+ .where(recurring_occurrences: { family_id: family.id })
+ 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
+ confirmed_allocations.pluck(:entry_id).to_set
end
# One query over the envelope of every open occurrence's window.
@@ -270,18 +563,47 @@ class RecurringTransaction
window_max = occurrences.map { |occurrence| window_for(occurrence).end }.max
window_max = Date.current if !include_closed_window && window_max > Date.current
+ reference_floor = if include_closed_window
+ occurrences.map(&:effective_due_on).min - 400
+ else
+ REFERENCE_LOOKBACK_DAYS.days.ago.to_date
+ end
+
source_account_ids = occurrences.map(&:recurring_transaction).select(&:transfer?).map(&:account_id).uniq
- preload_transfer_destinations(source_account_ids, window_min..window_max)
-
- family.entries
- .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id")
- .where(entryable_type: "Transaction")
- .not_excluded_or_split_parent
- .where(date: window_min..window_max)
- .where("transactions.kind NOT IN (?) OR transactions.id IN (?)", Transaction::TRANSFER_KINDS, transfer_destinations.keys)
- .where.not(id: RecurringAllocation.where.not(entry_id: nil).where(state: "confirmed").select(:entry_id))
- .includes(:entryable)
- .to_a
+ preload_transfer_destinations(source_account_ids, [ window_min, reference_floor ].min..[ window_max, Date.current ].max)
+
+ candidates_scope = family.entries
+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id")
+ .where(entryable_type: "Transaction")
+ .not_excluded_or_split_parent
+ .where("transactions.kind NOT IN (?) OR transactions.id IN (?)", Transaction::TRANSFER_KINDS, transfer_destinations.keys)
+ .where.not(id: confirmed_allocations.select(:entry_id))
+ .includes(:entryable)
+
+ by_window = candidates_scope.where(date: window_min..window_max).to_a
+ (by_window + reference_entries(candidates_scope, occurrences, reference_floor)).uniq(&:id)
+ end
+
+ # Entries whose note carries a bill's reference, wherever they fall in
+ # time: they are not inside any window by definition. The SQL is a coarse
+ # prefilter; matched_reference makes the exact whitespace-insensitive call.
+ def reference_entries(scope, occurrences, floor)
+ series_list = occurrences.map(&:recurring_transaction).uniq.select { |series| series.account_id.present? && !series.typed_income? }
+ needles = series_list.filter_map { |series| series.bank_reference && normalize_name(series.bank_reference) }
+ .select { |needle| needle.length >= MIN_REFERENCE_LENGTH }.uniq
+ return [] if needles.empty?
+
+ # A recurring transfer's reference may sit on the receiving leg only.
+ self.class.with_note_patterns(scope.where(account_id: series_list.map(&:account_id).uniq).where(entries: { date: floor..Date.current }), like_patterns(needles)).to_a
+ end
+
+ # More than one cycle before the series' first cycle: a payment from before
+ # the bill existed in this app, not that cycle's payment.
+ def before_first_cycle?(series, entry, earliest_due)
+ return false if earliest_due.nil?
+
+ cycle_days = (365.25 / series.schedule.occurrences_per_year).floor
+ entry.date < earliest_due - cycle_days
end
# Outflow transaction id => the account its transfer pays into, for the
@@ -296,14 +618,23 @@ class RecurringTransaction
.joins(outflow_transaction: :entry)
.joins("INNER JOIN entries inflow_entries ON inflow_entries.entryable_id = transfers.inflow_transaction_id AND inflow_entries.entryable_type = 'Transaction'")
.where(entries: { account_id: account_ids, date: dates })
- .pluck(:outflow_transaction_id, "inflow_entries.account_id")
- .each { |outflow_id, account_id| transfer_destinations[outflow_id] = account_id }
+ .pluck(:outflow_transaction_id, "inflow_entries.account_id", "inflow_entries.notes")
+ .each do |outflow_id, account_id, notes|
+ transfer_destinations[outflow_id] = account_id
+ transfer_inflow_notes[outflow_id] = notes
+ end
end
def transfer_destinations
@transfer_destinations ||= {}
end
+ # Outflow transaction id => the note on the receiving side of its
+ # transfer, filled alongside transfer_destinations.
+ def transfer_inflow_notes
+ @transfer_inflow_notes ||= {}
+ end
+
# The account the entry pays into when it is the outflow of a transfer.
# Read from the preload during candidate collection; looked up on demand
# for explain and orphan repair, which handle one entry at a time.
@@ -311,10 +642,12 @@ class RecurringTransaction
transaction_id = entry.entryable_id
return transfer_destinations[transaction_id] if transfer_destinations.key?(transaction_id) || @transfer_destinations_complete
- transfer_destinations[transaction_id] = Transfer
+ account_id, notes = Transfer
.where(outflow_transaction_id: transaction_id)
.joins(inflow_transaction: :entry)
- .pick("entries.account_id")
+ .pick("entries.account_id", "entries.notes")
+ transfer_inflow_notes[transaction_id] = notes
+ transfer_destinations[transaction_id] = account_id
end
# The occurrence's date window, snooze-aware and clamped so adjacent
@@ -348,9 +681,16 @@ class RecurringTransaction
# 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)
+ # The hard filters of identity_matches? hold for a repost too: a payment
+ # of the other sign, or a transfer leg of an ordinary bill, is never it.
+ return false if series.amount.positive? != entry.amount.positive?
+ return false if !series.transfer? && entry.entryable.transfer?
+
# A transfer leg's name is generic ("Transfer", a bank reference), so
# the account pair is the identity here too, as in identity_matches?.
+ return reference_only_identity?(series, entry) if reference_only?(series)
return transfer_destination(entry) == series.destination_account_id if series.transfer?
+ return true if reference_identity?(series, entry)
if series.merchant_id.present? && entry.entryable.merchant_id.present?
return entry.entryable.merchant_id == series.merchant_id
@@ -364,7 +704,8 @@ class RecurringTransaction
# 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). A recurring
+ # related (same merchant, a name the series knows, or the series' bank
+ # reference in the entry's note). A recurring
# transfer is identified by its account pair instead: the entry must be
# the outflow of a transfer into the series' destination account. Any
# other series never matches a transfer leg.
@@ -375,8 +716,10 @@ class RecurringTransaction
expense_series = series.amount.positive?
return false if expense_series != entry.amount.positive?
+ return reference_only_identity?(series, entry) if reference_only?(series)
return transfer_destination(entry) == series.destination_account_id if series.transfer?
return false if entry.entryable.transfer?
+ return true if reference_identity?(series, entry)
if series.merchant_id.present?
entry.entryable.merchant_id == series.merchant_id
@@ -385,6 +728,39 @@ class RecurringTransaction
end
end
+ # The user's own bank reference found in the note identifies the payee, so a
+ # bill named freely ("Strom") still finds its payment ("Example Energy").
+ # Bounded like every reference effect (see matched_reference), and a merchant
+ # the series is explicitly bound to is never overridden: an entry carrying a
+ # different merchant is that merchant's charge whatever its note says. An
+ # entry without a merchant has made no contrary claim.
+ def reference_identity?(series, entry)
+ return false if matched_reference(series, entry).nil?
+
+ entry_merchant_id = entry.entryable.merchant_id
+ !(series.merchant_id.present? && entry_merchant_id.present? && entry_merchant_id != series.merchant_id)
+ end
+
+ # "Match by reference only": the note's reference is the whole identity.
+ # Only effective where a reference can match at all (see matched_reference),
+ # otherwise the series keeps its ordinary identity rather than matching
+ # nothing.
+ def reference_only?(series)
+ series.reference_only? && !series.typed_income? && series.account_id.present?
+ end
+
+ # A recurring transfer additionally keeps its account pair; for every other
+ # series name and merchant are not compared at all.
+ def reference_only_identity?(series, entry)
+ if series.transfer?
+ return false unless transfer_destination(entry) == series.destination_account_id
+ elsif entry.entryable.transfer?
+ return false
+ end
+
+ matched_reference(series, entry).present?
+ end
+
def known_names(series)
@known_names ||= {}
@known_names[series.id] ||= series.known_names
@@ -406,22 +782,101 @@ class RecurringTransaction
def score(occurrence, series, entry)
signals = {}
expected = expected_for(occurrence)
+ reference = matched_reference(series, entry)
- if series.transfer?
- signals[:transfer] = 0.40
+ # Another bill's reference on this payment, and not this bill's own,
+ # excludes the candidate outright.
+ return [ BigDecimal("0"), signals ] if reference.nil? && conflicting_reference?(series, entry)
+
+ identity_key, identity_weight = if series.transfer?
+ [ :transfer, 0.40 ]
elsif series.merchant_id.present?
- signals[:merchant] = 0.40
+ [ :merchant, 0.40 ]
else
- signals[:name] = 0.35
+ [ :name, 0.35 ]
end
+ reference_only = reference_only?(series)
+ # Reference-only: the reference takes the identity's points below, and
+ # name or merchant give no signal.
+ signals[identity_key] = identity_weight unless reference_only
signals[:amount] = amount_score(series, expected, entry.amount.abs)
- return [ BigDecimal("0"), signals ] if signals[:amount].nil?
+ if signals[:amount].nil?
+ # Outside tolerance kills a candidate, unless the reference vouches
+ # for it: then the amount is only a fact about this payment (shown as
+ # "off by"), worth no points.
+ return [ BigDecimal("0"), signals ] unless reference
+
+ signals[:amount] = 0.0
+ end
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 ]
+ total = signals.values.sum.to_d
+ if reference
+ total += reference_only ? identity_weight.to_d : REFERENCE_BONUS
+ # Whatever the amount scored, a reference match is at least exact tier.
+ total = [ total, EXACT_TIER ].max
+ # Only the configured reference is stored, never the note it was found in.
+ signals[:reference] = reference
+ end
+
+ [ total.round(4), signals ]
+ end
+
+ # The series' configured bank reference when the entry's note carries it,
+ # else nil. Needs an account-scoped, non-income series: income notes come
+ # from the payer and income never reaches the review queue, so a spoofed
+ # deposit note would only ever be able to auto-link, and without an account
+ # nothing anchors the claim.
+ def matched_reference(series, entry)
+ return nil if series.typed_income? || series.account_id.blank?
+
+ reference = series.bank_reference
+ return nil if reference.nil?
+
+ needle = normalize_name(reference)
+ return nil if needle.length < MIN_REFERENCE_LENGTH
+
+ reference if note_texts(series, entry).any? { |text| normalize_name(text).include?(needle) }
+ end
+
+ # Another active bill on the entry's account carries a reference the note
+ # names, and this series' own reference did not match.
+ def conflicting_reference?(series, entry)
+ return false if series.typed_income?
+
+ others = references_by_account[entry.account_id]
+ return false if others.blank?
+
+ texts = note_texts(series, entry).map { |text| normalize_name(text) }
+ others.any? { |series_id, needle| series_id != series.id && texts.any? { |text| text.include?(needle) } }
+ end
+
+ # The entry's own note, plus the receiving side's for a recurring transfer
+ # (either leg's bank text may carry the reference).
+ def note_texts(series, entry)
+ texts = [ entry.notes ]
+ if series.transfer? && transfer_destination(entry)
+ texts << transfer_inflow_notes[entry.entryable_id]
+ end
+ texts.compact_blank
+ end
+
+ # account_id => [[series id, normalized reference]] over active non-income
+ # series, for the cross-series conflict check.
+ def references_by_account
+ @references_by_account ||= family.recurring_transactions.active
+ .where.not(account_id: nil)
+ .where.not("matcher_hints->>'bank_reference' IS NULL")
+ .reject(&:typed_income?)
+ .filter_map do |other|
+ needle = normalize_name(other.bank_reference)
+ [ other.account_id, [ other.id, needle ] ] if needle.length >= MIN_REFERENCE_LENGTH
+ end
+ .group_by(&:first)
+ .transform_values { |pairs| pairs.map(&:last) }
end
# Exact amount scores 0.30; within tolerance decays 0.25 -> 0.15 with
diff --git a/app/views/bills/_detail.html.erb b/app/views/bills/_detail.html.erb
index f329776df3..b1eba391ed 100644
--- a/app/views/bills/_detail.html.erb
+++ b/app/views/bills/_detail.html.erb
@@ -13,8 +13,14 @@
<%# Why this bill matches what it matches, in words rather than engine terms. %>
<div class="space-y-1.5">
<p class="text-xs font-medium text-secondary uppercase"><%= t("bills.detail.rules") %></p>
+ <%# What the app has learned from corrections, prepared by
+ BillsHelper#bills_matcher_hints. %>
+ <% hints = bills_matcher_hints(series) %>
<div class="flex flex-wrap gap-1.5">
- <%= render DS::Pill.new(label: t("bills.detail.rule_named", name: series.merchant&.name.presence || series.name), tone: :neutral, marker: false) %>
+ <%# A reference-only bill is not matched by its name, so the name is not offered as the rule. %>
+ <% unless hints[:reference_only] %>
+ <%= render DS::Pill.new(label: t("bills.detail.rule_named", name: series.merchant&.name.presence || series.name), tone: :neutral, marker: false) %>
+ <% end %>
<% amount_label = series.has_amount_variance? ?
t("bills.detail.rule_amount_range", min: format_money(series.expected_amount_min_money), max: format_money(series.expected_amount_max_money)) :
format_money(Money.new(series.amount.abs, series.currency)) %>
@@ -25,15 +31,17 @@
<% end %>
</div>
- <%# What the app has learned from corrections, prepared by
- BillsHelper#bills_matcher_hints. %>
- <% hints = bills_matcher_hints(series) %>
- <% if hints[:aliases].any? %>
+ <% if hints[:reference].present? %>
+ <p class="text-xs text-secondary">
+ <%= t(hints[:reference_only] ? "bills.detail.rule_reference_only" : "bills.detail.rule_reference", reference: hints[:reference]) %>
+ </p>
+ <% end %>
+ <% if !hints[:reference_only] && hints[:aliases].any? %>
<p class="text-xs text-secondary">
<%= t("bills.detail.rule_aliases", names: hints[:aliases].to_sentence) %>
</p>
<% end %>
- <% if hints[:detected_name].present? && hints[:detected_name] != (series.merchant&.name.presence || series.name) %>
+ <% if !hints[:reference_only] && hints[:detected_name].present? && hints[:detected_name] != (series.merchant&.name.presence || series.name) %>
<p class="text-xs text-secondary">
<%= t("bills.detail.rule_detected", name: hints[:detected_name]) %>
</p>
diff --git a/app/views/recurring_transactions/_form.html.erb b/app/views/recurring_transactions/_form.html.erb
index fd9ae52281..afccdb64a5 100644
--- a/app/views/recurring_transactions/_form.html.erb
+++ b/app/views/recurring_transactions/_form.html.erb
@@ -213,6 +213,21 @@
<p class="text-xs text-secondary"><%= t(".payment_url_hint") %></p>
</div>
+ <div class="space-y-2">
+ <%= f.text_field :bank_reference,
+ label: t(".bank_reference_label"),
+ placeholder: t(".bank_reference_placeholder") %>
+ <p class="text-xs text-secondary"><%= t(".bank_reference_hint") %></p>
+ </div>
+
+ <div class="flex items-start justify-between gap-4">
+ <div>
+ <p class="text-sm font-medium text-primary"><%= t(".reference_only_label") %></p>
+ <p class="text-xs text-secondary"><%= t(".reference_only_hint") %></p>
+ </div>
+ <%= f.toggle :reference_only %>
+ </div>
+
<div class="flex items-start justify-between gap-4">
<div>
<p class="text-sm font-medium text-primary"><%= t(".autopay_label") %></p>
diff --git a/config/brakeman.ignore b/config/brakeman.ignore
index d5939e3153..13efb588c4 100644
--- a/config/brakeman.ignore
+++ b/config/brakeman.ignore
@@ -199,13 +199,13 @@
{
"warning_type": "Mass Assignment",
"warning_code": 105,
- "fingerprint": "58922d7449ed00df3f1dbe574362416f1e9bee31afeb8675a3db3e91b87a9fdc",
+ "fingerprint": "06aa57f757847b932d40821c525a9f66dd8b33807bc65831d46db57b211255d1",
"check_name": "PermitAttributes",
"message": "Potentially dangerous key allowed for mass assignment",
"file": "app/controllers/recurring_transactions_controller.rb",
- "line": 379,
+ "line": 405,
"link": "https://brakemanscanner.org/docs/warning_types/mass_assignment/",
- "code": "params.require(:recurring_transaction).permit(:name, :amount, :currency, :account_id, :first_due_on, :frequency_preset, :frequency_interval, :frequency_interval_unit, :payment_url, :autopay, :notes, :is_income, :category_id)",
+ "code": "params.require(:recurring_transaction).permit(:name, :amount, :currency, :account_id, :first_due_on, :frequency_preset, :frequency_interval, :frequency_interval_unit, :payment_url, :autopay, :notes, :bank_reference, :reference_only, :is_income, :category_id)",
"render_path": null,
"location": {
"type": "controller",
diff --git a/config/locales/models/recurring_transaction/en.yml b/config/locales/models/recurring_transaction/en.yml
index 77befefc41..73e457a3ef 100644
--- a/config/locales/models/recurring_transaction/en.yml
+++ b/config/locales/models/recurring_transaction/en.yml
@@ -13,12 +13,15 @@ en:
attributes:
recurring_transaction:
payment_url: "Payment link"
+ bank_reference: "Bank reference"
frequency_interval: "Repeat interval"
errors:
models:
recurring_transaction:
merchant_or_name_required: "Either merchant or name must be present"
attributes:
+ bank_reference:
+ needs_account_and_expense: "only works on an expense bill with an account, because it is matched against that account's payments"
payment_url:
invalid_scheme: "must be a valid http:// or https:// address"
anchor_date:
diff --git a/config/locales/views/bills/en.yml b/config/locales/views/bills/en.yml
index cd9e1c1f19..320d8d704f 100644
--- a/config/locales/views/bills/en.yml
+++ b/config/locales/views/bills/en.yml
@@ -42,6 +42,8 @@ en:
once_kind_hint: Mark the transaction as one-time to keep it out of your averages.
rule_named: "%{name}"
rule_amount_range: "from %{min} to %{max}"
+ rule_reference: "Payments with \"%{reference}\" in the note match this bill, whatever the amount or date"
+ rule_reference_only: "Only payments with \"%{reference}\" in the note match this bill, whatever the amount or date"
rule_aliases: "Also matches %{names}"
rule_detected: "Matches transactions named %{name}"
rule_learned_tolerance: "Amounts within %{percent} of the usual amount match this bill"
@@ -101,6 +103,7 @@ en:
same_merchant: Same merchant
name_matches: Name matches
same_transfer: Transfer to the same account
+ reference: Payment note contains "%{reference}"
exact_amount: Exact amount
amount_off: "%{amount} off"
due_date: Due-date match
diff --git a/config/locales/views/recurring_transactions/en.yml b/config/locales/views/recurring_transactions/en.yml
index f34e2bcc92..1f72701864 100644
--- a/config/locales/views/recurring_transactions/en.yml
+++ b/config/locales/views/recurring_transactions/en.yml
@@ -110,6 +110,11 @@ en:
payment_url_label: Payment link
payment_url_placeholder: bank.example.com/pay
payment_url_hint: Where you go to pay this bill. Opens in a new tab from your recurring and upcoming lists.
+ bank_reference_label: Bank reference
+ bank_reference_placeholder: Contract or customer number
+ reference_only_label: Match by reference only
+ reference_only_hint: Ignore the bill's name and the payee; only payments whose note contains the reference match. Needs a bank reference.
+ bank_reference_hint: A stable token from the payment note (Verwendungszweck). Payments on this account whose note contains it match this bill whatever the amount or date, unless the payment carries a different merchant than a merchant-bound bill. Use something distinctive, at least 3 characters.
autopay_label: Pays automatically
autopay_hint: Keep it on your bills list, but stop treating it as something to do.
more_options: More options
diff --git a/test/controllers/bills_controller_test.rb b/test/controllers/bills_controller_test.rb
index fcd73f20be..341cbbc2a9 100644
--- a/test/controllers/bills_controller_test.rb
+++ b/test/controllers/bills_controller_test.rb
@@ -333,6 +333,29 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
assert_no_match "var(--color-destructive)", response.body
end
+ test "the drawer says which payment note identifies the bill, only when one is set" do
+ bill = create_bill(name: "Strom", amount: 80)
+ get_bill_history(bill)
+ assert_select "p.text-xs.text-secondary", text: /#{Regexp.escape(I18n.t("bills.detail.rule_reference", reference: "VN 4711"))}/, count: 0
+
+ bill.update!(bank_reference: "VN 4711")
+ get_bill_history(bill)
+
+ assert_select "p.text-xs.text-secondary", text: I18n.t("bills.detail.rule_reference", reference: "VN 4711"), count: 1
+ end
+
+ test "a reference-only bill's drawer shows the reference line and no name pill or name rules" do
+ bill = create_bill(name: "Strom", amount: 80)
+ bill.update!(matcher_hints: { "name_aliases" => [ "EXAMPLE" ] })
+ bill.update!(bank_reference: "VN 4711", reference_only: true)
+
+ get_bill_history(bill)
+
+ assert_select "p.text-xs.text-secondary", text: I18n.t("bills.detail.rule_reference_only", reference: "VN 4711"), count: 1
+ assert_select "p.text-xs.text-secondary", text: I18n.t("bills.detail.rule_aliases", names: "EXAMPLE"), count: 0
+ assert_select "span", text: "Strom", count: 0
+ end
+
test "the drawer names the detected bill only when it differs from the bill's name" do
bill = create_bill(name: "Netflix", amount: 15)
bill.update!(matcher_hints: { "detected_name" => "NETFLIX.COM" })
@@ -2787,9 +2810,8 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
response.body
end
- # Ending a bill leaves its scheduled occurrences behind, and the matcher
- # scores every scheduled occurrence, so it can still suggest a payment for a
- # bill the user deleted. The queue asks only about bills the page lists.
+ # Ending a bill leaves its scheduled occurrences behind with any suggestion
+ # made before, so it can still suggest a payment for a bill the user deleted. The queue asks only about bills the page lists.
test "a suggestion against an ended bill stays out of the payment review queue" do
due = Date.current - 3
bill = declare_bill(name: "OLD GYM", amount: 40, due: due)
diff --git a/test/controllers/recurring_occurrences_controller_test.rb b/test/controllers/recurring_occurrences_controller_test.rb
index 06fc0953b8..2cb064194d 100644
--- a/test/controllers/recurring_occurrences_controller_test.rb
+++ b/test/controllers/recurring_occurrences_controller_test.rb
@@ -206,6 +206,73 @@ class RecurringOccurrencesControllerTest < ActionDispatch::IntegrationTest
"the transaction matching the bill amount must survive the fifteen-row cut"
end
+ test "the picker ranks a payment carrying the bill's reference whatever its name or date" do
+ series = @family.recurring_transactions.create!(
+ name: "Strom", account: accounts(:depository), amount: 80, currency: "USD", expected_day_of_month: Date.current.day,
+ anchor_date: Date.current, last_occurrence_date: Date.current, next_expected_date: Date.current, status: "active",
+ manual: true, dedup_scope: "ref-picker", matcher_hints: { "bank_reference" => "VN 4711" }
+ )
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ far = accounts(:depository).entries.create!(
+ date: Date.current - 70, amount: 131.4, currency: "USD", name: "Example Energy", notes: "VN 4711 Abschlag", entryable: Transaction.new
+ )
+
+ get recurring_occurrence_url(occurrence), headers: { "Turbo-Frame" => "drawer" }
+
+ assert_includes @controller.view_assigns["ranked_candidates"].map { |entry, _| entry.id }, far.id
+ end
+
+ test "searching the fallback list finds a payment by its note" do
+ series = @family.recurring_transactions.create!(
+ name: "Strom", account: accounts(:depository), amount: 80, currency: "USD", expected_day_of_month: Date.current.day,
+ anchor_date: Date.current, last_occurrence_date: Date.current, next_expected_date: Date.current, status: "active",
+ manual: true, dedup_scope: "ref-search"
+ )
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ entry = accounts(:depository).entries.create!(
+ date: Date.current, amount: 55, currency: "USD", name: "Example Energy", notes: "contract 998877", entryable: Transaction.new
+ )
+
+ get recurring_occurrence_url(occurrence, q: "998877"), headers: { "Turbo-Frame" => "drawer" }
+
+ assert_includes @controller.view_assigns["other_entries"].map(&:id), entry.id
+ end
+
+ test "the picker's reference candidates are the ones nearest the occurrence when there are more than it scans" do
+ series = @family.recurring_transactions.create!(
+ name: "Strom", account: accounts(:depository), amount: 80, currency: "USD", expected_day_of_month: Date.current.day,
+ anchor_date: Date.current, last_occurrence_date: Date.current, next_expected_date: Date.current, status: "active",
+ manual: true, dedup_scope: "ref-limit", matcher_hints: { "bank_reference" => "VN 4711" }
+ )
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ with_scan_limit(2) do
+ accounts(:depository).entries.create!(date: occurrence.due_on - 300, amount: 80, currency: "USD", name: "old a", notes: "VN 4711", entryable: Transaction.new)
+ accounts(:depository).entries.create!(date: occurrence.due_on - 280, amount: 80, currency: "USD", name: "old b", notes: "VN 4711", entryable: Transaction.new)
+ near = accounts(:depository).entries.create!(date: [ occurrence.due_on, Date.current ].min, amount: 80, currency: "USD", name: "near", notes: "VN 4711", entryable: Transaction.new)
+
+ get recurring_occurrence_url(occurrence), headers: { "Turbo-Frame" => "drawer" }
+
+ assert_includes @controller.view_assigns["ranked_candidates"].map { |entry, _| entry.id }, near.id
+ end
+ end
+
+ test "the ranked list shows a reference payment ahead of better-scoring ordinary matches" do
+ series = @family.recurring_transactions.create!(
+ name: "Strom", account: accounts(:depository), amount: 80, currency: "USD", expected_day_of_month: Date.current.day,
+ anchor_date: Date.current, last_occurrence_date: Date.current, next_expected_date: Date.current, status: "active",
+ manual: true, dedup_scope: "ref-rank", matcher_hints: { "bank_reference" => "VN 4711" }
+ )
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ 8.times do
+ accounts(:depository).entries.create!(date: [ occurrence.due_on, Date.current ].min, amount: 80, currency: "USD", name: "Strom", entryable: Transaction.new)
+ end
+ ref = accounts(:depository).entries.create!(date: Date.current - 60, amount: 131.4, currency: "USD", name: "Example Energy", notes: "VN 4711", entryable: Transaction.new)
+
+ get recurring_occurrence_url(occurrence), headers: { "Turbo-Frame" => "drawer" }
+
+ assert_equal ref.id, @controller.view_assigns["ranked_candidates"].first.first.id
+ end
+
# The mission's own example. The picker ranked by amount distance and nothing
# else, so a $6.44 Twitch charge scored exactly as well as the $6.44 7-Eleven
# charge for a 7-Eleven bill. It now asks the matcher, whose identity filter
@@ -669,4 +736,14 @@ class RecurringOccurrencesControllerTest < ActionDispatch::IntegrationTest
)
series.recurring_occurrences.order(:due_on).first
end
+
+ def with_scan_limit(limit)
+ original = RecurringOccurrencesController::RANKED_SCAN_LIMIT
+ RecurringOccurrencesController.send(:remove_const, :RANKED_SCAN_LIMIT)
+ RecurringOccurrencesController.const_set(:RANKED_SCAN_LIMIT, limit)
+ yield
+ ensure
+ RecurringOccurrencesController.send(:remove_const, :RANKED_SCAN_LIMIT)
+ RecurringOccurrencesController.const_set(:RANKED_SCAN_LIMIT, original)
+ end
end
diff --git a/test/controllers/recurring_transactions_controller_test.rb b/test/controllers/recurring_transactions_controller_test.rb
index ba79a72ca5..3b5d8c4831 100644
--- a/test/controllers/recurring_transactions_controller_test.rb
+++ b/test/controllers/recurring_transactions_controller_test.rb
@@ -235,6 +235,33 @@ class RecurringTransactionsControllerTest < ActionDispatch::IntegrationTest
assert_equal "https://pay.example.com/bill", @recurring_transaction.reload.payment_url
end
+ test "update saves and clears a bank reference" do
+ patch recurring_transaction_url(@recurring_transaction),
+ params: { recurring_transaction: { bank_reference: "VN 4711" } }
+ assert_equal "VN 4711", @recurring_transaction.reload.bank_reference
+
+ patch recurring_transaction_url(@recurring_transaction),
+ params: { recurring_transaction: { bank_reference: "" } }
+ assert_nil @recurring_transaction.reload.bank_reference
+ end
+
+ test "update toggles match by reference only" do
+ patch recurring_transaction_url(@recurring_transaction),
+ params: { recurring_transaction: { bank_reference: "VN 4711", reference_only: "1" } }
+ assert @recurring_transaction.reload.reference_only?
+
+ patch recurring_transaction_url(@recurring_transaction),
+ params: { recurring_transaction: { bank_reference: "VN 4711", reference_only: "0" } }
+ assert_not @recurring_transaction.reload.reference_only?
+ end
+
+ test "edit offers the bank reference field" do
+ get edit_recurring_transaction_url(@recurring_transaction), headers: { "Turbo-Frame" => "modal" }
+
+ assert_match "recurring_transaction[bank_reference]", response.body
+ assert_match "recurring_transaction[reference_only]", response.body
+ end
+
test "new renders the create dialog in a single modal frame" do
get new_recurring_transaction_url, headers: { "Turbo-Frame" => "modal" }
diff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rb
index 4e1eb2dc44..d4b616ee30 100644
--- a/test/controllers/transactions_controller_test.rb
+++ b/test/controllers/transactions_controller_test.rb
@@ -77,6 +77,36 @@ class TransactionsControllerTest < ActionDispatch::IntegrationTest
assert_match(/für die am .* fällige Rechnung/, response.body)
end
+ test "the drawer lists only the active bill a payment paid, not an ended twin's allocation" do
+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))
+ due = Date.current.beginning_of_month + 8
+ series_for = lambda do |name, status|
+ series = @user.family.recurring_transactions.create!(
+ account: accounts(:depository), name: name, amount: 2000,
+ currency: "USD", expected_day_of_month: 9, status: status, manual: true,
+ bill_type: "bill", last_occurrence_date: Date.current,
+ next_expected_date: Date.current
+ )
+ series.recurring_occurrences.destroy_all
+ series.recurring_occurrences.create!(
+ family: @user.family, original_due_on: due, due_on: due,
+ currency: "USD", expected_amount: 2000, status: "scheduled"
+ )
+ end
+ ended = series_for.call("Ended Twin", "ended")
+ active = series_for.call("Active Twin", "active")
+ [ ended, active ].each do |occurrence|
+ occurrence.allocations.create!(entry: @entry, allocated_amount: 2000, currency: "USD",
+ source: "auto_matched", state: "confirmed")
+ end
+
+ get transaction_url(@entry), headers: { "Turbo-Frame" => "drawer" }
+
+ assert_response :success
+ assert_match "Active Twin", response.body
+ assert_no_match "Ended Twin", response.body
+ end
+
# The dialog route is GET only. Rendered as a button_to, "Create a bill"
# POSTed to it and the modal frame showed "Content Missing".
test "create a bill opens the prefilled dialog with a GET" do
diff --git a/test/helpers/bills_helper_test.rb b/test/helpers/bills_helper_test.rb
index 29cd8e6215..b935fbc0e0 100644
--- a/test/helpers/bills_helper_test.rb
+++ b/test/helpers/bills_helper_test.rb
@@ -55,6 +55,13 @@ class BillsHelperTest < ActionView::TestCase
assert_equal [ I18n.t("bills.match.same_transfer") ], reasons
end
+ test "a reference match is explained by the reference alone" do
+ reasons = bills_match_reasons({ name: 0.35, reference: "VN 4711", account: 0.10 }, currency: "USD")
+
+ assert_equal [ I18n.t("bills.match.reference", reference: "VN 4711"), I18n.t("bills.match.name_matches") ].sort, reasons.sort
+ end
+
+
# signals[:account] is a constant 0.10 on every candidate, because
# identity_matches? has already rejected everything on another account. A
# reason that never distinguishes anything is decoration.
@@ -512,6 +519,16 @@ class BillsHelperTest < ActionView::TestCase
assert_equal "NETFLIX.COM", bills_matcher_hints(series)[:detected_name]
end
+ test "matcher hints expose the bank reference when one was stored" do
+ assert_equal "VN 4711", bills_matcher_hints(OpenStruct.new(matcher_hints: { "bank_reference" => "VN 4711" }))[:reference]
+ assert_nil bills_matcher_hints(OpenStruct.new(matcher_hints: {}))[:reference]
+ end
+
+ test "matcher hints report reference-only only when a reference is set" do
+ assert bills_matcher_hints(OpenStruct.new(matcher_hints: { "bank_reference" => "VN 4711", "reference_only" => true }))[:reference_only]
+ assert_not bills_matcher_hints(OpenStruct.new(matcher_hints: { "reference_only" => true }))[:reference_only]
+ end
+
test "matcher hints leave the detected name nil when none was stored" do
series = OpenStruct.new(matcher_hints: {})
diff --git a/test/models/assistant/function/create_bill_test.rb b/test/models/assistant/function/create_bill_test.rb
index 4825430b7b..e5adaff566 100644
--- a/test/models/assistant/function/create_bill_test.rb
+++ b/test/models/assistant/function/create_bill_test.rb
@@ -42,6 +42,26 @@ class Assistant::Function::CreateBillTest < ActiveSupport::TestCase
assert_equal [ due ], series.recurring_occurrences.pluck(:due_on)
end
+ test "a bank reference is stored on the new bill" do
+ result = call_tool(
+ "name" => "City Water", "amount" => 80, "first_due_on" => (Date.current + 3).iso8601,
+ "account_name" => accounts(:depository).name, "bank_reference" => "VN 4711"
+ )
+
+ assert result[:created]
+ assert_equal "VN 4711", @family.recurring_transactions.find_by!(name: "City Water").bank_reference
+ end
+
+ test "reference_only is stored with the reference" do
+ result = call_tool(
+ "name" => "City Water", "amount" => 80, "first_due_on" => (Date.current + 3).iso8601,
+ "account_name" => accounts(:depository).name, "bank_reference" => "VN 4711", "reference_only" => true
+ )
+
+ assert result[:created]
+ assert @family.recurring_transactions.find_by!(name: "City Water").reference_only?
+ end
+
test "income flips the stored sign, never the caller's" do
result = call_tool(
"name" => "Paycheck", "amount" => 1200,
diff --git a/test/models/assistant/function/get_bill_details_test.rb b/test/models/assistant/function/get_bill_details_test.rb
index 20db358bc4..b6b8be7fe2 100644
--- a/test/models/assistant/function/get_bill_details_test.rb
+++ b/test/models/assistant/function/get_bill_details_test.rb
@@ -21,6 +21,13 @@ class Assistant::Function::GetBillDetailsTest < ActiveSupport::TestCase
assert_equal "$100.00", result[:analytics][:paid_this_year]
end
+ test "the bank reference that identifies payments is part of the bill" do
+ series = create_series(name: "Strom", amount: 80)
+ series.update!(bank_reference: "VN 4711")
+
+ assert_equal "VN 4711", call_tool(series.id)[:bill][:bank_reference]
+ end
+
test "analytics are null before anything was paid" do
series = create_series(name: "Fresh bill", amount: 50)
diff --git a/test/models/assistant/function/update_bill_test.rb b/test/models/assistant/function/update_bill_test.rb
index 02755d8b17..7e616db471 100644
--- a/test/models/assistant/function/update_bill_test.rb
+++ b/test/models/assistant/function/update_bill_test.rb
@@ -52,6 +52,41 @@ class Assistant::Function::UpdateBillTest < ActiveSupport::TestCase
"an AI-applied cadence is user intent by proxy; detection must not move it back"
end
+ test "bank_reference is set and cleared like the edit dialog does" do
+ series = create_series(name: "Water", amount: 80)
+
+ result = call_tool(series.id, "bank_reference" => "VN 4711")
+ assert result[:updated]
+ assert_includes result[:changed_fields], "bank_reference"
+ assert_equal "VN 4711", series.reload.bank_reference
+
+ call_tool(series.id, "bank_reference" => "")
+ assert_nil series.reload.bank_reference
+ end
+
+ test "reference_only is set through the tool and reported effective only with a reference" do
+ series = create_series(name: "Water", amount: 80)
+
+ result = call_tool(series.id, "bank_reference" => "VN 4711", "reference_only" => true)
+
+ assert result[:updated]
+ assert_includes result[:changed_fields], "reference_only"
+ assert series.reload.reference_only?
+ assert_equal true, result[:bill][:reference_only]
+
+ assert call_tool(series.id, "reference_only" => false)[:updated]
+ assert_not series.reload.reference_only?
+ end
+
+ test "a too short bank_reference is refused with the validation message" do
+ series = create_series(name: "Water", amount: 80)
+
+ result = call_tool(series.id, "bank_reference" => "ab")
+
+ assert result[:error].present?
+ assert_nil series.reload.bank_reference
+ end
+
test "paused maps to the stored value the UI's own Pause writes" do
series = create_series(name: "Gym", amount: 40)
diff --git a/test/models/recurring_transaction/history_backfiller_test.rb b/test/models/recurring_transaction/history_backfiller_test.rb
index 1fc45f9c5b..935544d1ad 100644
--- a/test/models/recurring_transaction/history_backfiller_test.rb
+++ b/test/models/recurring_transaction/history_backfiller_test.rb
@@ -28,6 +28,64 @@ class RecurringTransaction::HistoryBackfillerTest < ActiveSupport::TestCase
end
end
+ test "a variable-amount bill with a bank reference keeps its history instead of being pruned" do
+ travel_to Date.new(2026, 8, 10) do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: -1)
+ series.update!(bank_reference: "VN 4711")
+ create_entry(amount: 131.40, date: Date.new(2026, 7, 9), name: "CITY WATER", notes: "VN 4711 Abschlag")
+ create_entry(amount: 52.10, date: Date.new(2026, 6, 9), name: "CITY WATER", notes: "VN 4711 Abschlag")
+
+ Backfiller.new(@family, months: 4).run!
+
+ assert_includes series.recurring_occurrences.paid.pluck(:due_on), Date.new(2026, 7, 9)
+ # Underpaid, so linked but not closed; the point is that it is not pruned.
+ june = series.recurring_occurrences.find_by!(due_on: Date.new(2026, 6, 9))
+ assert_equal 52.10, june.allocations.sole.allocated_amount.to_f
+ end
+ end
+
+ # Live case: a quarterly insurance whose premium dropped 15% for four quarters
+ # and then came back, every payment carrying the reference.
+ test "a deviating payment identified by the reference is linked and its occurrence is never pruned" do
+ travel_to Date.new(2026, 11, 11) do
+ series = create_series(name: "Home Insurance", amount: 400.00, day_offset: 0)
+ series.update!(bank_reference: "POL-04-123456")
+ series.update_columns(expected_day_of_month: 12, anchor_date: Date.new(2025, 1, 12))
+ RecurringTransaction::FrequencyPreset.apply(series, preset: "quarterly", day_of_month: 12, month_of_year: 1)
+ series.save!
+
+ payments = { Date.new(2025, 4, 23) => 340.00, Date.new(2025, 7, 14) => 340.00, Date.new(2025, 10, 13) => 340.00,
+ Date.new(2026, 1, 12) => 340.00, Date.new(2026, 4, 13) => 400.00, Date.new(2026, 7, 13) => 400.00,
+ Date.new(2026, 10, 12) => 400.00 }
+ entries = payments.map { |date, amount| create_entry(amount: amount, date: date, name: "Example Insurer", notes: "POL-04-123456 Beitrag") }
+
+ Backfiller.new(@family, months: 24).run!
+
+ assert_equal 7, RecurringAllocation.where(entry_id: entries.map(&:id)).count
+ assert_includes series.recurring_occurrences.pluck(:due_on), Date.new(2026, 1, 12)
+ assert_equal 7, series.recurring_occurrences.paid.count,
+ "a payment the reference identified settles its quarter whatever its amount"
+ assert_equal 340.00, series.recurring_occurrences.find_by!(due_on: Date.new(2026, 1, 12)).allocations.sole.allocated_amount.to_f
+ end
+ end
+
+ test "two reference payments around one due date both link to that occurrence" do
+ travel_to Date.new(2026, 11, 11) do
+ series = create_series(name: "Example Energy", amount: 150, day_offset: -1)
+ series.update!(bank_reference: "Example")
+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.new(2026, 5, 1))
+ # Due on the 10th: both payments are nearest to the July occurrence.
+ first = create_entry(amount: 160.00, date: Date.new(2026, 7, 18), name: "Example Energy", notes: "Example Abschlag")
+ second = create_entry(amount: 140.00, date: Date.new(2026, 7, 22), name: "Example Energy", notes: "Example Abschlag")
+
+ Backfiller.new(@family, months: 8).run!
+
+ allocations = RecurringAllocation.where(entry_id: [ first.id, second.id ])
+ assert_equal 2, allocations.count, "neither payment of the cycle may be dropped"
+ assert_equal 1, allocations.distinct.count(:recurring_occurrence_id)
+ 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)
@@ -101,9 +159,10 @@ class RecurringTransaction::HistoryBackfillerTest < ActiveSupport::TestCase
)
end
- def create_entry(amount:, date:, name:)
+ def create_entry(amount:, date:, name:, notes: nil)
@account.entries.create!(
date: date,
+ notes: notes,
amount: amount,
currency: "USD",
name: name,
diff --git a/test/models/recurring_transaction/identifier_test.rb b/test/models/recurring_transaction/identifier_test.rb
index 137730fd31..942b6c1f22 100644
--- a/test/models/recurring_transaction/identifier_test.rb
+++ b/test/models/recurring_transaction/identifier_test.rb
@@ -1006,6 +1006,17 @@ class RecurringTransaction::IdentifierTest < ActiveSupport::TestCase
assert_equal categories(:one), oldest_minority.reload.category
end
+ test "a detected series restricted to its reference is not refreshed from name groups" do
+ account = @family.accounts.first
+ detected = create_detected_series(account: account, name: "Pet Cover", amount: 54.73, day: 5)
+ detected.update!(bank_reference: "PET 123", reference_only: true)
+ create_name_pattern_entries(account: account, name: "Pet Cover", amount: 54.73, day: 5)
+
+ @identifier.identify_recurring_patterns
+
+ assert_not_equal 3, detected.reload.occurrence_count, "the reference-only series must not be refreshed by name"
+ end
+
# No categorised entry means no category to take: the series stays blank and
# the run still completes (an empty tally gives max_by nothing, not an error).
test "uncategorised entries leave a blank series blank" do
diff --git a/test/models/recurring_transaction/matcher_test.rb b/test/models/recurring_transaction/matcher_test.rb
index 563da3b4dc..5c485ccd4a 100644
--- a/test/models/recurring_transaction/matcher_test.rb
+++ b/test/models/recurring_transaction/matcher_test.rb
@@ -513,8 +513,867 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCase
assert_nil Matcher.new(@family).explain(occurrence, other)
end
+ # An ended series (a deleted or dismissed bill) is a tombstone, as for the
+ # Allocator: the payments it holds stay with it as history, but they can be
+ # linked again by an active series.
+ test "an active transfer series links the payments an ended detected twin holds" do
+ ended = create_series(name: "Allowance", amount: 250, day_offset: -10, destination: accounts(:loan), bill_type: "transfer", dedup_scope: "detected")
+ active = create_series(name: "Allowance", amount: 250, day_offset: -10, destination: accounts(:loan), bill_type: "transfer", dedup_scope: "manual")
+ [ ended, active ].each { |series| RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 130) }
+ cycles = ended.recurring_occurrences.order(:due_on).first(3)
+ entries = cycles.map { |cycle| create_transfer(amount: 250, date: cycle.due_on, to: accounts(:loan)) }
+ held = entries.zip(cycles).map do |entry, cycle|
+ RecurringTransaction::Allocator.new(cycle).allocate_matched!(entry: entry, state: "confirmed", confidence: 1, signals: { transfer: true })
+ end
+ ended.update_columns(status: "ended")
+
+ @matcher.run_backfill!
+
+ assert_equal entries.map(&:id).sort, RecurringAllocation.joins(:recurring_occurrence)
+ .where(recurring_occurrences: { recurring_transaction_id: active.id }).pluck(:entry_id).sort
+ assert_equal held.map(&:id).sort, RecurringAllocation.joins(:recurring_occurrence)
+ .where(recurring_occurrences: { recurring_transaction_id: ended.id }).pluck(:id).sort
+ end
+
+ test "linking from an ended series is idempotent" do
+ ended = create_series(name: "CITY WATER", amount: 80, day_offset: -10, dedup_scope: "old")
+ active = create_series(name: "CITY WATER", amount: 80, day_offset: -10, dedup_scope: "new")
+ [ ended, active ].each { |series| RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 100) }
+ cycle = ended.recurring_occurrences.order(:due_on).first
+ entry = create_entry(amount: 80, date: cycle.due_on, name: "CITY WATER")
+ RecurringTransaction::Allocator.new(cycle).allocate_matched!(entry: entry, state: "confirmed", confidence: 1, signals: { name: true })
+ ended.update_columns(status: "ended")
+
+ @matcher.run_backfill!
+ state = RecurringAllocation.order(:id).pluck(:entry_id, :recurring_occurrence_id, :state)
+ Matcher.new(@family).run_backfill!
+
+ assert_equal state, RecurringAllocation.order(:id).pluck(:entry_id, :recurring_occurrence_id, :state)
+ assert_equal [ ended.id, active.id ].sort, RecurringAllocation.where(entry_id: entry.id).map { |a| a.recurring_occurrence.recurring_transaction_id }.sort
+ end
+
+ test "a live run links a payment an ended duplicate holds to the active bill" do
+ ended = create_series(name: "CITY WATER", amount: 80, day_offset: -10, dedup_scope: "old")
+ active = create_series(name: "CITY WATER", amount: 80, day_offset: -10, dedup_scope: "new")
+ [ ended, active ].each { |series| RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 40) }
+ cycle = ended.recurring_occurrences.where(due_on: ..Date.current).order(:due_on).last
+ entry = create_entry(amount: 80, date: cycle.due_on, name: "CITY WATER")
+ RecurringTransaction::Allocator.new(cycle).allocate_matched!(entry: entry, state: "confirmed", confidence: 1, signals: { name: true })
+ ended.update_columns(status: "ended")
+
+ @matcher.run!
+
+ assert RecurringAllocation.joins(:recurring_occurrence)
+ .exists?(entry_id: entry.id, recurring_occurrences: { recurring_transaction_id: active.id })
+ end
+
+ test "an ended series' own open cycles do not make a payment ambiguous for the active twin" do
+ ended = create_series(name: "CITY WATER", amount: 80, day_offset: -10, dedup_scope: "old")
+ active = create_series(name: "CITY WATER", amount: 80, day_offset: -10, dedup_scope: "new")
+ [ ended, active ].each { |series| RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 40) }
+ cycle = active.recurring_occurrences.order(:due_on).first
+ entry = create_entry(amount: 80, date: cycle.due_on, name: "CITY WATER")
+ ended.update_columns(status: "ended")
+
+ @matcher.run_backfill!
+
+ assert_equal cycle.id, RecurringAllocation.find_by!(entry_id: entry.id).recurring_occurrence_id
+ end
+
+ test "an ended series keeps its allocation when no active series matches the payment" do
+ ended = create_series(name: "CITY WATER", amount: 80, day_offset: -10)
+ RecurringTransaction::OccurrenceGenerator.new(ended).backfill!(from: Date.current - 100)
+ cycle = ended.recurring_occurrences.order(:due_on).first
+ entry = create_entry(amount: 80, date: cycle.due_on, name: "CITY WATER")
+ allocation = RecurringTransaction::Allocator.new(cycle).allocate_matched!(entry: entry, state: "confirmed", confidence: 1, signals: { name: true })
+ ended.update_columns(status: "ended")
+
+ @matcher.run_backfill!
+
+ assert RecurringAllocation.exists?(allocation.id)
+ end
+
+ test "a person's own link on an ended series is never removed" do
+ ended = create_series(name: "CITY WATER", amount: 80, day_offset: -10, dedup_scope: "old")
+ create_series(name: "CITY WATER", amount: 80, day_offset: -10, dedup_scope: "new")
+ RecurringTransaction::OccurrenceGenerator.new(ended).backfill!(from: Date.current - 100)
+ cycle = ended.recurring_occurrences.order(:due_on).first
+ entry = create_entry(amount: 80, date: cycle.due_on, name: "CITY WATER")
+ chosen = cycle.allocations.create!(entry: entry, allocated_amount: 80, currency: "USD", state: "confirmed", source: "user_confirmed", paid_on: entry.date)
+ ended.update_columns(status: "ended")
+
+ @matcher.run_backfill!
+
+ assert RecurringAllocation.exists?(chosen.id)
+ end
+
+ test "an active series the person rejected for a payment does not take it from an ended one" do
+ ended = create_series(name: "CITY WATER", amount: 80, day_offset: -10, dedup_scope: "old")
+ active = create_series(name: "CITY WATER", amount: 80, day_offset: -10, dedup_scope: "new")
+ RecurringTransaction::OccurrenceGenerator.new(ended).backfill!(from: Date.current - 100)
+ RecurringTransaction::OccurrenceGenerator.new(active).backfill!(from: Date.current - 100)
+ cycle = ended.recurring_occurrences.order(:due_on).first
+ entry = create_entry(amount: 80, date: cycle.due_on, name: "CITY WATER")
+ allocation = RecurringTransaction::Allocator.new(cycle).allocate_matched!(entry: entry, state: "confirmed", confidence: 1, signals: { name: true })
+ RecurringMatchRejection.create!(recurring_transaction: active, entry: entry)
+ ended.update_columns(status: "ended")
+
+ @matcher.run_backfill!
+
+ assert_equal [ allocation.id ], RecurringAllocation.where(entry_id: entry.id).pluck(:id)
+ end
+
+ test "a paused series still takes a late payment into its open cycle" do
+ paused = create_series(name: "CITY WATER", amount: 80, day_offset: -10)
+ RecurringTransaction::OccurrenceGenerator.new(paused).backfill!(from: Date.current - 40)
+ cycle = paused.recurring_occurrences.order(:due_on).first
+ entry = create_entry(amount: 80, date: cycle.due_on, name: "CITY WATER")
+ paused.update_columns(status: "paused")
+
+ @matcher.run_backfill!
+
+ assert_equal cycle.id, RecurringAllocation.find_by!(entry_id: entry.id).recurring_occurrence_id
+ end
+
+ # --- Bank reference (Verwendungszweck) -------------------------------------
+
+ test "a bank reference lets a variable bill link although the amount is outside tolerance" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ entry = create_entry(amount: 130, date: Date.current, name: "CITY WATER", notes: "VN 4711 Abschlag Nov, IBAN DE02 1234")
+
+ assert_equal 1, @matcher.run!
+
+ allocation = occurrence.allocations.sole
+ assert_equal entry.id, allocation.entry_id
+ assert allocation.allocation_confirmed?
+ assert_equal "VN 4711", allocation.match_signals["reference"],
+ "only the matched reference is stored"
+ assert_not_includes allocation.match_signals.to_json, "IBAN",
+ "the third-party note itself is never persisted"
+ end
+
+ test "the same variable payment without a reference stays unmatched" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0)
+ create_entry(amount: 130, date: Date.current, name: "CITY WATER", notes: "VN 4711 Abschlag")
+
+ assert_equal 0, @matcher.run!
+ assert_equal 0, series.recurring_occurrences.order(:due_on).first.allocations.count
+ end
+
+ test "a reference payment settles its cycle at half the expected figure, showing the real amount paid" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ half = create_entry(amount: 40, date: Date.current, name: "CITY WATER", notes: "VN 4711")
+
+ assert_equal 1, @matcher.run!
+
+ allocation = occurrence.allocations.sole
+ assert_equal half.id, allocation.entry_id
+ assert allocation.allocation_confirmed?
+ assert_equal 40, allocation.allocated_amount.to_f
+ assert occurrence.reload.paid?, "the reference says this is the cycle's payment, whatever it amounted to"
+ end
+
+ test "a reference payment of three times the expected figure is allocated whole and settles the cycle" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ entry = create_entry(amount: 240, date: Date.current, name: "CITY WATER", notes: "VN 4711")
+
+ assert_equal 1, @matcher.run!
+
+ allocation = occurrence.allocations.sole
+ assert_equal 240, allocation.allocated_amount.to_f, "the real paid amount, not what the cycle still needed"
+ assert occurrence.reload.paid?
+ assert_equal 0, @matcher.run!, "a second run neither stacks nor raises on the used-up entry"
+ assert_equal entry.id, occurrence.allocations.sole.entry_id
+ end
+
+ test "a series without a reference still needs a payment within tolerance to settle its cycle" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0)
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ create_entry(amount: 81, date: Date.current, name: "CITY WATER")
+ @matcher.run!
+ assert occurrence.reload.paid?
+
+ other = create_series(name: "POWER CO", amount: 100, day_offset: 0)
+ other_occurrence = other.recurring_occurrences.order(:due_on).first
+ create_entry(amount: 60, date: Date.current, name: "POWER CO")
+ @matcher.run!
+ assert_equal 0, other_occurrence.reload.allocations.count, "amount outside tolerance never matches without a reference"
+ end
+
+ test "a reference match with an off amount is only a suggestion for a pending charge" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ create_entry(amount: 130, date: Date.current, name: "CITY WATER", notes: "VN 4711",
+ extra: { "simplefin" => { "pending" => true } })
+
+ @matcher.run!
+
+ assert series.recurring_occurrences.order(:due_on).first.allocations.sole.allocation_suggested?
+ end
+
+ test "reference matching ignores case and runs of whitespace" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "vn 4711" })
+ create_entry(amount: 130, date: Date.current, name: "CITY WATER", notes: "Abschlag VN\n4711 Nov")
+
+ assert_equal 1, @matcher.run!
+ assert series.recurring_occurrences.order(:due_on).first.allocations.sole.match_signals.key?("reference")
+ end
+
+ test "a note naming the reference on another account cannot pull in a foreign charge" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ accounts(:credit_card).entries.create!(
+ date: Date.current, amount: 130, currency: "USD", name: "CITY WATER", notes: "VN 4711",
+ entryable: Transaction.new
+ )
+
+ assert_equal 0, @matcher.run!
+ assert_equal 0, series.recurring_occurrences.order(:due_on).first.allocations.count
+ end
+
+ test "an absent note or reference changes no score" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ plain = create_entry(amount: 80, date: Date.current, name: "CITY WATER")
+ other_note = create_entry(amount: 80, date: Date.current, name: "CITY WATER", notes: "something else")
+
+ baseline = @matcher.explain(occurrence, plain)
+ assert_equal baseline.confidence, @matcher.explain(occurrence, other_note).confidence
+ assert_not baseline.signals.key?(:reference)
+ end
+
+ test "a reference match breaks a tie between two otherwise identical bills" do
+ first = create_series(name: "GYM", amount: 40, day_offset: 0, dedup_scope: "a", hints: { "bank_reference" => "KV-111" })
+ second = create_series(name: "GYM", amount: 40, day_offset: 0, dedup_scope: "b", hints: { "bank_reference" => "KV-222" })
+ entry = create_entry(amount: 40, date: Date.current, name: "GYM", notes: "KV-222 membership")
+
+ assert_equal 1, @matcher.run!
+
+ assert_equal 0, first.recurring_occurrences.order(:due_on).first.allocations.count
+ allocation = second.recurring_occurrences.order(:due_on).first.allocations.sole
+ assert_equal entry.id, allocation.entry_id
+ assert allocation.allocation_confirmed?
+ end
+
+ test "a note naming another series' reference on the same account excludes this series" do
+ mine = create_series(name: "GYM", amount: 40, day_offset: 0, dedup_scope: "a", hints: { "bank_reference" => "KV-111" })
+ create_series(name: "GYM", amount: 40, day_offset: 0, dedup_scope: "b", hints: { "bank_reference" => "KV-222" })
+ entry = create_entry(amount: 40, date: Date.current, name: "GYM", notes: "KV-222")
+
+ assert_nil @matcher.explain(mine.recurring_occurrences.order(:due_on).first, entry)
+ end
+
+ test "a reference match is exact tier even with a far-off amount and signals the deviation" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ entry = create_entry(amount: 400, date: Date.current - 1, name: "CITY WATER", notes: "VN 4711")
+
+ explanation = @matcher.explain(series.recurring_occurrences.order(:due_on).first, entry)
+
+ assert_operator explanation.confidence, :>=, Matcher::EXACT_TIER
+ assert_equal "VN 4711", explanation.signals[:reference]
+ assert_equal 0.0, explanation.signals[:amount]
+ end
+
+ test "a second reference payment in the same cycle is linked as an extra payment on that occurrence" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ first = create_entry(amount: 80, date: Date.current, name: "CITY WATER", notes: "VN 4711")
+ second = create_entry(amount: 95, date: Date.current - 1, name: "CITY WATER", notes: "VN 4711")
+
+ assert_equal 2, @matcher.run!
+
+ assert_equal [ first.id, second.id ].sort, occurrence.allocations.pluck(:entry_id).sort
+ assert occurrence.reload.paid?
+ assert_equal 0, Matcher.new(@family).run!, "no duplicate links on rerun"
+ assert_equal 2, occurrence.allocations.count
+ end
+
+ test "a reference payment arriving after the cycle was paid is linked on a later run" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ create_entry(amount: 80, date: Date.current, name: "CITY WATER", notes: "VN 4711")
+ @matcher.run!
+ assert occurrence.reload.paid?
+
+ later = create_entry(amount: 70, date: Date.current, name: "CITY WATER", notes: "VN 4711 Nachzahlung")
+ assert_equal 1, Matcher.new(@family).run!
+
+ assert_equal 2, occurrence.allocations.count
+ assert_includes occurrence.allocations.pluck(:entry_id), later.id
+ assert_equal 0, Matcher.new(@family).run!
+ end
+
+ test "a run closes an occurrence whose reference allocation was linked before the settle rule existed" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ create_entry(amount: 60, date: Date.current, name: "CITY WATER", notes: "VN 4711")
+ @matcher.run!
+ occurrence.reload.reopen!
+ assert occurrence.reload.scheduled?
+
+ assert_equal 0, Matcher.new(@family).run_backfill!
+
+ assert occurrence.reload.paid?, "the existing reference allocation settles the cycle on the next run"
+ assert_equal 60, occurrence.allocations.sole.allocated_amount.to_f
+ end
+
+ test "a stale suggestion for a reference payment is confirmed instead of blocking the link" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ entry = create_entry(amount: 70, date: Date.current, name: "CITY WATER", notes: "VN 4711")
+ occurrence.allocations.create!(entry: entry, allocated_amount: 70, currency: "USD", source_amount: 70, source_currency: "USD",
+ state: "suggested", source: "auto_matched", match_confidence: 0.7, match_signals: {}, paid_on: entry.date)
+
+ assert_equal 1, Matcher.new(@family).run_backfill!
+
+ allocation = occurrence.allocations.sole
+ assert allocation.allocation_confirmed?
+ assert occurrence.reload.paid?
+ end
+
+ test "a stale suggestion on another occurrence does not use up the entry the reference now links" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ other = series.recurring_occurrences.order(:due_on).second
+ assert other, "a later cycle exists"
+ entry = create_entry(amount: 70, date: Date.current, name: "CITY WATER", notes: "VN 4711")
+ other.allocations.create!(entry: entry, allocated_amount: 70, currency: "USD", source_amount: 70, source_currency: "USD",
+ state: "suggested", source: "auto_matched", match_confidence: 0.7, match_signals: {}, paid_on: entry.date)
+
+ assert_equal 1, Matcher.new(@family).run_backfill!
+
+ assert_equal [ occurrence.id ], RecurringAllocation.where(entry_id: entry.id).pluck(:recurring_occurrence_id)
+ assert RecurringAllocation.find_by!(entry_id: entry.id).allocation_confirmed?
+ end
+
+
+ test "a paid occurrence takes no extra payment without the reference" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ create_entry(amount: 80, date: Date.current, name: "CITY WATER", notes: "VN 4711")
+ @matcher.run!
+
+ create_entry(amount: 80, date: Date.current, name: "CITY WATER", notes: "no reference")
+
+ assert_equal 0, Matcher.new(@family).run!
+ assert_equal 1, occurrence.allocations.count
+ end
+
+ test "a reference payment links regardless of the date window: three days before the due date" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 3, hints: { "bank_reference" => "VN 4711" })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ entry = create_entry(amount: 80, date: Date.current, name: "CITY WATER", notes: "VN 4711")
+
+ assert_equal 1, @matcher.run!
+
+ assert_equal entry.id, occurrence.allocations.sole.entry_id
+ assert occurrence.reload.paid?
+ end
+
+ test "without the reference the same early payment stays outside the window" do
+ create_series(name: "CITY WATER", amount: 80, day_offset: 3)
+ create_entry(amount: 80, date: Date.current, name: "CITY WATER", notes: "no reference")
+
+ assert_equal 0, @matcher.run!
+ end
+
+ test "a reference payment goes to the nearest occurrence by due date, whatever the distance" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ occurrences = series.recurring_occurrences.order(:due_on).to_a
+ later = occurrences.second
+ assert later, "a later cycle exists"
+ entry = create_entry(amount: 80, date: later.due_on - 11, name: "CITY WATER", notes: "VN 4711")
+
+ Matcher.new(@family).run_backfill!
+
+ assert_equal later.id, RecurringAllocation.find_by!(entry_id: entry.id).recurring_occurrence_id
+ end
+
+ # The reference only says which bill; the month is date arithmetic. A payment
+ # that arrives late goes to the oldest open overdue cycle inside the matching
+ # window, even when the next cycle is nearer by due date.
+ test "a late reference payment settles the oldest open overdue cycle, not the nearer next one" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: -45, hints: { "bank_reference" => "VN 4711" })
+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 100)
+ overdue, following = series.recurring_occurrences.order(:due_on).select(&:scheduled?).first(2)
+ entry = create_entry(amount: 80, date: overdue.due_on + 20, name: "CITY WATER", notes: "VN 4711")
+ assert_operator (following.due_on - entry.date).to_i, :<, 20, "the next cycle is the nearer one"
+
+ Matcher.new(@family).run_backfill!
+
+ assert_equal overdue.id, RecurringAllocation.find_by!(entry_id: entry.id).recurring_occurrence_id
+ assert overdue.reload.paid?
+ assert following.reload.scheduled?
+ end
+
+ test "the same late payment without the reference still goes to the nearest cycle in its window" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: -45)
+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 100)
+ overdue, following = series.recurring_occurrences.order(:due_on).select(&:scheduled?).first(2)
+ entry = create_entry(amount: 80, date: overdue.due_on + 20, name: "CITY WATER")
+
+ Matcher.new(@family).run!
+
+ allocation = RecurringAllocation.find_by!(entry_id: entry.id)
+ assert_equal overdue.id, allocation.recurring_occurrence_id
+ assert following.reload.scheduled?
+ end
+
+ test "a run re-homes a late reference payment confirmed on the next cycle to the overdue one" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: -45, hints: { "bank_reference" => "VN 4711" })
+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 100)
+ overdue, following = series.recurring_occurrences.order(:due_on).select(&:scheduled?).first(2)
+ entry = create_entry(amount: 80, date: overdue.due_on + 20, name: "CITY WATER", notes: "VN 4711")
+ stale = RecurringTransaction::Allocator.new(following).allocate_matched!(entry: entry, state: "confirmed", confidence: 1, signals: { reference: "VN 4711" })
+
+ Matcher.new(@family).run_backfill!
+
+ assert_equal overdue.id, stale.reload.recurring_occurrence_id
+ assert overdue.reload.paid?
+ assert following.reload.scheduled?
+ end
+
+ test "a tie between a paid and an open occurrence goes to the open one" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: -10, hints: { "bank_reference" => "VN 4711" })
+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 100)
+ first, second = series.recurring_occurrences.order(:due_on).first(2)
+ create_entry(amount: 80, date: first.due_on, name: "CITY WATER", notes: "VN 4711")
+ @matcher.run!
+ assert first.reload.paid?
+ midpoint = first.due_on + ((second.due_on - first.due_on).to_i / 2)
+ entry = create_entry(amount: 80, date: midpoint, name: "CITY WATER", notes: "VN 4711")
+ tie = (entry.date - first.due_on).to_i == (second.due_on - entry.date).to_i
+
+ Matcher.new(@family).run!
+
+ expected = tie ? second : (entry.date - first.due_on).to_i < (second.due_on - entry.date).to_i ? first : second
+ assert_equal expected.id, RecurringAllocation.find_by!(entry_id: entry.id).recurring_occurrence_id
+ end
+
+ test "a reference payment long before the series' first cycle is left alone without error" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ old = create_entry(amount: 80, date: Date.current - 400, name: "CITY WATER", notes: "VN 4711")
+
+ assert_equal 0, Matcher.new(@family).run_backfill!
+ assert_equal 0, RecurringAllocation.where(entry_id: old.id).count
+ assert_operator series.recurring_occurrences.count, :>, 0
+ end
+
+ test "a reference payment within a cycle before the series' first cycle attaches to that first cycle" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ first = series.recurring_occurrences.order(:due_on).first
+ entry = create_entry(amount: 80, date: first.due_on - 20, name: "CITY WATER", notes: "VN 4711")
+
+ assert_equal 1, Matcher.new(@family).run_backfill!
+ assert_equal first.id, RecurringAllocation.find_by!(entry_id: entry.id).recurring_occurrence_id
+ end
+
+ # Earlier builds paired a payment with a farther cycle when the nearest one
+ # was taken; those confirmed allocations are re-homed to the nearest cycle.
+ test "a run re-homes an auto-created reference allocation to the nearest cycle and swaps the cycles' states" do
+ series = create_series(name: "Home Loan", amount: 1200.00, day_offset: -40, hints: { "bank_reference" => "REF 123 456" })
+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 140)
+ cycles = series.recurring_occurrences.order(:due_on).to_a
+ old_cycle = cycles.first
+ near = cycles.find { |cycle| cycle.due_on >= Date.current - 40 } || cycles.last
+ (cycles - [ old_cycle, near ]).each { |cycle| cycle.close!("skipped", source: "user") }
+ entry = create_entry(amount: 1200.00, date: near.due_on - 3, name: "Example Bank", notes: "REF 123 456 Rate")
+ stale = RecurringTransaction::Allocator.new(old_cycle).allocate_matched!(entry: entry, state: "confirmed", confidence: 1, signals: { reference: "REF 123 456" })
+ assert old_cycle.reload.paid?
+
+ @matcher.run_backfill!
+
+ assert_equal near.id, stale.reload.recurring_occurrence_id, "moved to the nearest cycle"
+ assert_equal 1, RecurringAllocation.where(entry_id: entry.id).count
+ assert near.reload.paid?
+ assert old_cycle.reload.scheduled?, "the cycle it was wrongly settling is open again"
+ end
+
+ # Two bills for the same payee and amount told apart only by their references:
+ # a confirmed name-identity allocation of one bill sitting on a payment that
+ # carries the other bill's reference is released so the right bill can link it.
+ test "a run releases a confirmed auto allocation whose note names another bill's reference and the other bill links it" do
+ alex = create_series(name: "Lens Plan", amount: 20.90, day_offset: -10, hints: { "bank_reference" => "Lens Plan Alex" })
+ sam = create_series(name: "Lens Plan", amount: 20.90, day_offset: -10, dedup_scope: "sam", hints: { "bank_reference" => "Lens Plan Sam" })
+ [ alex, sam ].each { |series| RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 100) }
+ month = alex.recurring_occurrences.where(due_on: ..Date.current).order(:due_on).last
+ own = create_entry(amount: 20.90, date: month.due_on, name: "Lens Shop", notes: "Lens Plan Alex")
+ foreign = create_entry(amount: 20.90, date: month.due_on, name: "Lens Shop", notes: "Lens Plan Sam")
+ allocator = RecurringTransaction::Allocator.new(month)
+ allocator.allocate_matched!(entry: own, state: "confirmed", confidence: 1, signals: { reference: "Lens Plan Alex" })
+ allocator.allocate_matched!(entry: foreign, state: "confirmed", confidence: 1, signals: { name: true })
+
+ @matcher.run_backfill!
+
+ assert_equal [ own.id ], alex.recurring_occurrences.flat_map { |cycle| cycle.allocations.pluck(:entry_id) }
+ assert_equal [ foreign.id ], sam.recurring_occurrences.flat_map { |cycle| cycle.allocations.pluck(:entry_id) }
+ assert sam.recurring_occurrences.where(due_on: ..Date.current).order(:due_on).last.reload.paid?
+ end
+
+ test "releasing foreign-reference allocations is idempotent" do
+ alex = create_series(name: "Lens Plan", amount: 20.90, day_offset: -10, hints: { "bank_reference" => "Lens Plan Alex" })
+ sam = create_series(name: "Lens Plan", amount: 20.90, day_offset: -10, dedup_scope: "sam", hints: { "bank_reference" => "Lens Plan Sam" })
+ [ alex, sam ].each { |series| RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 100) }
+ month = alex.recurring_occurrences.order(:due_on).first
+ foreign = create_entry(amount: 20.90, date: month.due_on, name: "Lens Shop", notes: "Lens Plan Sam")
+ RecurringTransaction::Allocator.new(month).allocate_matched!(entry: foreign, state: "confirmed", confidence: 1, signals: { name: true })
+
+ @matcher.run_backfill!
+ state = RecurringAllocation.order(:id).pluck(:entry_id, :recurring_occurrence_id, :state)
+ Matcher.new(@family).run_backfill!
+
+ assert_equal state, RecurringAllocation.order(:id).pluck(:entry_id, :recurring_occurrence_id, :state)
+ end
+
+ test "a person's own choice is never released for naming another bill's reference" do
+ alex = create_series(name: "Lens Plan", amount: 20.90, day_offset: -10, hints: { "bank_reference" => "Lens Plan Alex" })
+ create_series(name: "Lens Plan", amount: 20.90, day_offset: -10, dedup_scope: "sam", hints: { "bank_reference" => "Lens Plan Sam" })
+ month = RecurringTransaction::OccurrenceGenerator.new(alex).backfill!(from: Date.current - 100) && alex.recurring_occurrences.order(:due_on).first
+ entry = create_entry(amount: 20.90, date: month.due_on, name: "Lens Shop", notes: "Lens Plan Sam")
+ chosen = month.allocations.create!(entry: entry, allocated_amount: 20.90, currency: "USD", state: "confirmed", source: "user_confirmed", paid_on: entry.date)
+
+ @matcher.run_backfill!
+
+ assert RecurringAllocation.exists?(chosen.id)
+ end
+
+ test "a reference-only bill releases an auto allocation whose note lacks its reference" do
+ series = create_series(name: "Lens Plan", amount: 20.90, day_offset: -10, hints: { "bank_reference" => "Lens Plan Alex", "reference_only" => true })
+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 100)
+ month = series.recurring_occurrences.order(:due_on).last
+ bare = create_entry(amount: 20.90, date: month.due_on, name: "Lens Plan", notes: "monthly fee")
+ kept = create_entry(amount: 20.90, date: month.due_on, name: "Lens Shop", notes: "Lens Plan Alex")
+ allocator = RecurringTransaction::Allocator.new(month)
+ allocator.allocate_matched!(entry: bare, state: "confirmed", confidence: 1, signals: { name: true })
+ allocator.allocate_matched!(entry: kept, state: "confirmed", confidence: 1, signals: { reference: "Lens Plan Alex" })
+
+ @matcher.run_backfill!
+
+ assert_nil RecurringAllocation.find_by(entry_id: bare.id)
+ assert RecurringAllocation.exists?(entry_id: kept.id)
+ end
+
+ test "a reference-only bill leaves paid older cycles untouched when the note lacks the reference" do
+ series = create_series(name: "Lens Plan", amount: 20.90, day_offset: -10, hints: { "bank_reference" => "Lens Plan Alex", "reference_only" => true })
+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 160)
+ older = series.recurring_occurrences.order(:due_on).first(3)
+ allocations = older.map do |cycle|
+ entry = create_entry(amount: 20.90, date: cycle.due_on, name: "Lens Plan", notes: "monthly fee")
+ RecurringTransaction::Allocator.new(cycle).allocate_matched!(entry: entry, state: "confirmed", confidence: 1, signals: { name: true })
+ end
+ assert older.all? { |cycle| cycle.reload.paid? }
+
+ @matcher.run_backfill!
+ Matcher.new(@family).run!
+
+ allocations.each { |allocation| assert RecurringAllocation.exists?(allocation.id) }
+ assert older.all? { |cycle| cycle.reload.paid? }
+ end
+
+ test "reconciliation only loads allocations on a reference-only bill, with a reference signal, or whose note names a reference" do
+ watched = create_series(name: "City Water", amount: 80, day_offset: -10, dedup_scope: "w", hints: { "bank_reference" => "VN 4711" })
+ only = create_series(name: "Lens Plan", amount: 20.90, day_offset: -10, dedup_scope: "o", hints: { "bank_reference" => "Lens Plan Alex", "reference_only" => true })
+ plain = create_series(name: "Rent", amount: 900, day_offset: -10, dedup_scope: "p")
+ bystander = create_series(name: "Gym", amount: 30, day_offset: -10, dedup_scope: "b")
+ [ watched, only, plain, bystander ].each { |series| RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 40) }
+
+ link = lambda do |series, amount, notes, signals|
+ cycle = series.recurring_occurrences.order(:due_on).first
+ entry = create_entry(amount: amount, date: cycle.due_on, name: series.name, notes: notes)
+ RecurringTransaction::Allocator.new(cycle).allocate_matched!(entry: entry, state: "confirmed", confidence: 1, signals: signals)
+ entry
+ end
+ on_reference_only = link.call(only, 20.90, "monthly fee", { name: true })
+ with_signal = link.call(watched, 80, "unrelated text", { reference: "VN 4711" })
+ naming_reference = link.call(plain, 900, "paid VN 4711 by mistake", { name: true })
+ link.call(bystander, 30, "membership", { name: true })
+
+ seen = []
+ RecurringTransaction::Matcher.any_instance.stubs(:contradicted_allocation?).with { |_, entry| seen << entry.id }.returns(false)
+
+ Matcher.new(@family).run!
+
+ assert_equal [ on_reference_only.id, with_signal.id, naming_reference.id ].sort, seen.uniq.sort
+ end
+
+ test "re-homing is idempotent" do
+ series = create_series(name: "Home Loan", amount: 100, day_offset: -40, hints: { "bank_reference" => "REF 123 456" })
+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 140)
+ cycles = series.recurring_occurrences.order(:due_on).to_a
+ near = cycles.find { |cycle| cycle.due_on >= Date.current - 40 } || cycles.last
+ entry = create_entry(amount: 100, date: near.due_on, name: "Example Bank", notes: "REF 123 456")
+ RecurringTransaction::Allocator.new(cycles.first).allocate_matched!(entry: entry, state: "confirmed", confidence: 1, signals: { reference: "REF 123 456" })
+
+ @matcher.run_backfill!
+ snapshot = RecurringAllocation.pluck(:id, :recurring_occurrence_id, :updated_at)
+ Matcher.new(@family).run_backfill!
+ Matcher.new(@family).run!
+
+ assert_equal snapshot, RecurringAllocation.pluck(:id, :recurring_occurrence_id, :updated_at)
+ end
+
+ test "re-homing never touches hand-made or non-reference allocations" do
+ series = create_series(name: "Home Loan", amount: 100, day_offset: -40, hints: { "bank_reference" => "REF 123 456" })
+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 140)
+ cycles = series.recurring_occurrences.order(:due_on).to_a
+ far = cycles.first
+ near = cycles.find { |cycle| cycle.due_on >= Date.current - 40 } || cycles.last
+ by_hand = create_entry(amount: 100, date: near.due_on, name: "Example Bank", notes: "REF 123 456")
+ no_signal = create_entry(amount: 100, date: near.due_on - 1, name: "Example Bank", notes: "REF 123 456")
+ kept = RecurringTransaction::Allocator.new(far).allocate_matched!(entry: no_signal, state: "confirmed", confidence: 1, signals: { name: 0.35 })
+ hand = far.allocations.create!(entry: by_hand, allocated_amount: 100, currency: "USD", source_amount: 100, source_currency: "USD",
+ state: "confirmed", source: "user_confirmed", match_signals: { "reference" => "REF 123 456" }, paid_on: by_hand.date)
+
+ @matcher.run_backfill!
+
+ assert_equal far.id, hand.reload.recurring_occurrence_id, "a user's own choice stays"
+ assert_equal far.id, kept.reload.recurring_occurrence_id, "an allocation without the reference signal stays"
+ end
+
+
+ test "a rejected reference payment is never linked, however near" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: 3, hints: { "bank_reference" => "VN 4711" })
+ entry = create_entry(amount: 80, date: Date.current, name: "CITY WATER", notes: "VN 4711")
+ RecurringMatchRejection.create!(recurring_transaction: series, entry: entry)
+
+ assert_equal 0, @matcher.run!
+ end
+
+ test "reference identity matches whatever the amount" do
+ create_series(name: "Strom", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ create_entry(amount: 400, date: Date.current, name: "Example Energy GmbH", notes: "VN 4711")
+
+ assert_equal 1, @matcher.run!
+ end
+
+ test "reference identity still needs the right sign and account" do
+ create_series(name: "Strom", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ create_entry(amount: -80, date: Date.current, name: "Example Energy GmbH", notes: "VN 4711")
+ accounts(:credit_card).entries.create!(
+ date: Date.current, amount: 80, currency: "USD", name: "Example", notes: "VN 4711", entryable: Transaction.new
+ )
+
+ assert_equal 0, @matcher.run!
+ end
+
+ test "a differently named payee without the reference still does not match" do
+ create_series(name: "Strom", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ create_entry(amount: 80, date: Date.current, name: "Example Energy GmbH", notes: "other contract")
+
+ assert_equal 0, @matcher.run!
+ end
+
+ test "a reference never makes an ordinary bill claim a transfer leg" do
+ create_series(name: "Strom", amount: 500, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ create_transfer(amount: 500, date: Date.current, to: accounts(:loan), notes: "VN 4711")
+
+ assert_equal 0, @matcher.run!
+ end
+
+ test "explain accepts a reference-identified payee" do
+ series = create_series(name: "Strom", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ entry = create_entry(amount: 80, date: Date.current, name: "Example Energy GmbH", notes: "VN 4711")
+
+ assert_not_nil @matcher.explain(series.recurring_occurrences.order(:due_on).first, entry)
+ end
+
+ test "repair re-attaches a reposted payment by reference although its name changed" do
+ series = create_series(name: "Strom", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ original = create_entry(amount: 80, date: Date.current, name: "Example Energy GmbH", notes: "VN 4711")
+ @matcher.run!
+ allocation = occurrence.allocations.sole
+ original.destroy!
+ replacement = create_entry(amount: 80, date: allocation.paid_on, name: "PENDING EXAMPLE", notes: "VN 4711")
+
+ Matcher.new(@family).repair_orphans!
+
+ assert_equal replacement.id, allocation.reload.entry_id
+ end
+
+ test "reference-only: the reference is the only identity, a matching name without it never links" do
+ series = create_series(name: "Strom", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711", "reference_only" => true })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ create_entry(amount: 80, date: Date.current, name: "Strom", notes: "other contract")
+ assert_equal 0, @matcher.run!
+
+ entry = create_entry(amount: 80, date: Date.current, name: "Example Energy GmbH", notes: "VN 4711")
+ assert_equal 1, @matcher.run!
+ assert_equal entry.id, occurrence.allocations.sole.entry_id
+ end
+
+ test "reference-only does not compare the merchant" do
+ series = create_series(name: nil, merchant: merchants(:netflix), amount: 80, day_offset: 0,
+ hints: { "bank_reference" => "VN 4711", "reference_only" => true })
+ create_entry(amount: 80, date: Date.current, name: "Other", merchant: merchants(:amazon), notes: "VN 4711")
+
+ assert_equal 1, @matcher.run!
+ assert_equal 1, series.recurring_occurrences.order(:due_on).first.allocations.count
+ end
+
+ test "reference-only scores the reference in place of the name, so scores are not inflated" do
+ series = create_series(name: "Strom", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711", "reference_only" => true })
+ entry = create_entry(amount: 80, date: Date.current, name: "Example", notes: "VN 4711")
+
+ explanation = @matcher.explain(series.recurring_occurrences.order(:due_on).first, entry)
+
+ assert_equal "VN 4711", explanation.signals[:reference]
+ assert_not explanation.signals.key?(:name)
+ assert_not explanation.signals.key?(:merchant)
+ assert_in_delta 0.95, explanation.confidence, 0.001
+ end
+
+ test "reference-only is ignored without a reference" do
+ create_series(name: "Strom", amount: 80, day_offset: 0, hints: { "reference_only" => true })
+ create_entry(amount: 80, date: Date.current, name: "Strom")
+
+ assert_equal 1, @matcher.run!
+ end
+
+ test "reference-only keeps account and sign" do
+ create_series(name: "Strom", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711", "reference_only" => true })
+ create_entry(amount: -80, date: Date.current, name: "Example", notes: "VN 4711")
+ accounts(:credit_card).entries.create!(
+ date: Date.current, amount: 80, currency: "USD", name: "Example", notes: "VN 4711", entryable: Transaction.new
+ )
+
+ assert_equal 0, @matcher.run!
+ end
+
+ test "reference-only on a recurring transfer needs the account pair and the reference" do
+ series = create_series(name: "Transfer one", amount: 2000, day_offset: 0, destination: accounts(:loan), bill_type: "transfer",
+ hints: { "bank_reference" => "Contract_1", "reference_only" => true })
+ create_transfer(amount: 2000, date: Date.current, to: accounts(:loan), notes: "no reference")
+ create_transfer(amount: 2000, date: Date.current, to: accounts(:credit_card), notes: "Contract_1")
+ assert_equal 0, @matcher.run!
+
+ entry = create_transfer(amount: 2000, date: Date.current, to: accounts(:loan), notes: "Contract_1")
+ assert_equal 1, @matcher.run!
+ assert_equal entry.id, series.recurring_occurrences.order(:due_on).first.allocations.sole.entry_id
+ end
+
+ test "reference-only repair re-attaches only an entry carrying the reference" do
+ series = create_series(name: "Strom", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711", "reference_only" => true })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ original = create_entry(amount: 80, date: Date.current, name: "Example", notes: "VN 4711")
+ @matcher.run!
+ allocation = occurrence.allocations.sole
+ original.destroy!
+ create_entry(amount: 80, date: allocation.paid_on, name: "Strom", notes: "other")
+ replacement = create_entry(amount: 80, date: allocation.paid_on, name: "Whatever", notes: "VN 4711")
+
+ Matcher.new(@family).repair_orphans!
+
+ assert_equal replacement.id, allocation.reload.entry_id
+ end
+
+ test "backfill closes a variable bill's past occurrence by reference" do
+ series = create_series(name: "CITY WATER", amount: 80, day_offset: -40, hints: { "bank_reference" => "VN 4711" })
+ occurrence = series.recurring_occurrences.order(:due_on).first
+ create_entry(amount: 130, date: occurrence.due_on, name: "CITY WATER", notes: "VN 4711")
+
+ @matcher.run_backfill!
+
+ assert occurrence.reload.paid?
+ end
+
+ # --- review follow-ups -----------------------------------------------------
+
+ test "a future-dated entry carrying the reference settles nothing in a live run" do
+ series = create_series(name: "Strom", amount: 80, day_offset: 2, hints: { "bank_reference" => "VN 4711" })
+ create_entry(amount: 80, date: Date.current + 5, name: "Example Energy", notes: "VN 4711")
+
+ assert_equal 0, @matcher.run!
+ assert_empty series.recurring_occurrences.flat_map(&:allocations)
+ end
+
+ test "a recurring transfer whose reference is only on the receiving leg links outside the date window" do
+ series = create_series(name: "Allowance", amount: 250, day_offset: -3, destination: accounts(:loan), bill_type: "transfer",
+ hints: { "bank_reference" => "ALLOW 77" })
+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 100)
+ entry = create_transfer(amount: 250, date: Date.current - 118, to: accounts(:loan), notes: "plain", inflow_notes: "ALLOW 77 monthly")
+
+ assert_operator @matcher.run_backfill!, :>=, 1
+ assert RecurringAllocation.exists?(entry_id: entry.id)
+ end
+
+ test "a reference payment nearer an old settled annual cycle than the next one lands on the old cycle" do
+ due = Date.current - 250
+ series = create_series(name: "Insurance", amount: 400, day_offset: -250, hints: { "bank_reference" => "POL 55" })
+ RecurringTransaction::FrequencyPreset.apply(series, preset: "annual", day_of_month: due.day, month_of_year: due.month)
+ series.save!
+ series.recurring_occurrences.destroy_all
+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: due - 1)
+ RecurringTransaction::OccurrenceGenerator.new(series).generate!
+ old_cycle = series.recurring_occurrences.order(:due_on).first
+ assert_equal due, old_cycle.due_on
+ first = create_entry(amount: 400, date: due, name: "Example Insurer", notes: "POL 55")
+ RecurringTransaction::Allocator.new(old_cycle).allocate_matched!(entry: first, state: "confirmed", confidence: 1, signals: { reference: "POL 55" })
+ assert old_cycle.reload.paid?
+ extra = create_entry(amount: 120, date: due + 170, name: "Example Insurer", notes: "POL 55 extra")
+
+ @matcher.run!
+
+ assert_equal old_cycle.id, RecurringAllocation.find_by!(entry_id: extra.id).recurring_occurrence_id
+ end
+
+ test "orphan repair never re-attaches an opposite-sign entry or a transfer leg to an ordinary bill by reference" do
+ series = create_series(name: "Strom", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ original = create_entry(amount: 80, date: Date.current, name: "Example Energy", notes: "VN 4711")
+ @matcher.run!
+ allocation = series.recurring_occurrences.order(:due_on).first.allocations.sole
+ original.destroy!
+ create_entry(amount: -80, date: allocation.paid_on, name: "Example Energy", notes: "VN 4711")
+ create_transfer(amount: 80, date: allocation.paid_on, to: accounts(:loan), notes: "VN 4711")
+
+ Matcher.new(@family).repair_orphans!
+
+ assert_nil allocation.reload.entry_id
+ end
+
+ test "a payment moved to its nearest cycle replaces a suggestion the entry holds there and keeps both cycles consistent" do
+ series = create_series(name: "Home Loan", amount: 1200.00, day_offset: -40, hints: { "bank_reference" => "REF 123 456" })
+ RecurringTransaction::OccurrenceGenerator.new(series).backfill!(from: Date.current - 140)
+ cycles = series.recurring_occurrences.order(:due_on).to_a
+ old_cycle = cycles.first
+ near = cycles.find { |cycle| cycle.due_on >= Date.current - 40 } || cycles.last
+ (cycles - [ old_cycle, near ]).each { |cycle| cycle.close!("skipped", source: "user") }
+ entry = create_entry(amount: 1200.00, date: near.due_on - 3, name: "Example Bank", notes: "REF 123 456 Rate")
+ confirmed = RecurringTransaction::Allocator.new(old_cycle).allocate_matched!(entry: entry, state: "confirmed", confidence: 1, signals: { reference: "REF 123 456" })
+ near.allocations.create!(entry: entry, allocated_amount: 10, currency: "USD", state: "suggested", source: "auto_matched", match_confidence: 0.7, match_signals: {}, paid_on: entry.date)
+
+ @matcher.run_backfill!
+
+ assert_equal near.id, confirmed.reload.recurring_occurrence_id
+ assert_equal [ "confirmed" ], RecurringAllocation.where(entry_id: entry.id).pluck(:state)
+ assert near.reload.paid?
+ assert old_cycle.reload.scheduled?
+ end
+
+ test "two bills matching the same reference through different paths stay ambiguous" do
+ ordinary = create_series(name: "Strom", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ only = create_series(name: "Other name", amount: 80, day_offset: 0, dedup_scope: "only", hints: { "bank_reference" => "VN 4711", "reference_only" => true })
+ entry = create_entry(amount: 80, date: Date.current, name: "Strom", notes: "VN 4711")
+
+ @matcher.run!
+
+ assert_empty RecurringAllocation.confirmed.where(entry_id: entry.id), "a tie is never auto-confirmed"
+ assert ordinary.present? && only.present?
+ end
+
+ test "two bills matching the same reference are resolved by how well the payment fits" do
+ close = create_series(name: "Strom", amount: 80, day_offset: 0, hints: { "bank_reference" => "VN 4711" })
+ create_series(name: "Strom", amount: 80, day_offset: 20, dedup_scope: "far", hints: { "bank_reference" => "VN 4711" })
+ entry = create_entry(amount: 80, date: Date.current, name: "Strom", notes: "VN 4711")
+
+ @matcher.run!
+
+ assert_equal close.id, RecurringAllocation.find_by!(entry_id: entry.id).recurring_occurrence.recurring_transaction_id
+ end
+
private
- def create_series(amount:, day_offset:, name: nil, merchant: nil, dedup_scope: "", preset: "monthly", bill_type: "bill", destination: nil)
+ def create_series(amount:, day_offset:, name: nil, merchant: nil, dedup_scope: "", preset: "monthly", bill_type: "bill", destination: nil, hints: {})
due = Date.current + day_offset
series = @family.recurring_transactions.create!(
@@ -531,7 +1390,8 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCase
last_occurrence_date: due,
next_expected_date: due,
status: "active",
- manual: true
+ manual: true,
+ matcher_hints: hints
)
if preset != "monthly"
@@ -543,20 +1403,21 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCase
end
# The outflow leg of a confirmed transfer from @account into `to`.
- def create_transfer(amount:, date:, to:, name: "Transfer")
- outflow = create_entry(amount: amount, date: date, name: name)
+ def create_transfer(amount:, date:, to:, name: "Transfer", notes: nil, inflow_notes: nil)
+ outflow = create_entry(amount: amount, date: date, name: name, notes: notes)
outflow.entryable.update!(kind: "loan_payment")
inflow = to.entries.create!(
- date: date, amount: -amount, currency: "USD", name: name,
+ date: date, amount: -amount, currency: "USD", name: name, notes: inflow_notes,
entryable: Transaction.new(kind: "funds_movement")
)
Transfer.create!(outflow_transaction: outflow.entryable, inflow_transaction: inflow.entryable, status: "confirmed")
outflow
end
- def create_entry(amount:, date:, name: "charge", merchant: nil, extra: {})
+ def create_entry(amount:, date:, name: "charge", merchant: nil, extra: {}, notes: nil)
@account.entries.create!(
date: date,
+ notes: notes,
amount: amount,
currency: "USD",
name: name,
diff --git a/test/models/recurring_transaction/transfer_series_pipeline_test.rb b/test/models/recurring_transaction/transfer_series_pipeline_test.rb
new file mode 100644
index 0000000000..acd7e72aa8
--- /dev/null
+++ b/test/models/recurring_transaction/transfer_series_pipeline_test.rb
@@ -0,0 +1,54 @@
+require "test_helper"
+
+class RecurringTransaction::TransferSeriesPipelineTest < ActiveSupport::TestCase
+ def setup
+ @family = families(:dylan_family)
+ @account = accounts(:depository)
+ @destination = accounts(:loan)
+ @family.recurring_transactions.destroy_all
+ end
+
+ test "a transfer series made by mark-as-recurring links every exact-day outflow through the whole pipeline, next to sibling transfer series" do
+ travel_to Date.new(2026, 11, 3) do
+ dates = [ Date.new(2026, 5, 1), Date.new(2026, 6, 1), Date.new(2026, 7, 2), Date.new(2026, 8, 3),
+ Date.new(2026, 9, 2), Date.new(2026, 10, 1), Date.new(2026, 11, 3) ]
+ transfers = dates.map { |date| create_transfer(amount: 250, date: date, to: @destination) }
+ allowance = from_transfer(transfers.first, day: 3)
+
+ shopping = dates.map { |date| create_transfer(amount: 500, date: date, to: accounts(:credit_card)) }
+ from_transfer(shopping.first, day: 3)
+ contracts = [ [ "Contract_1", accounts(:investment) ], [ "Contract_2", accounts(:property) ] ].map do |reference, to|
+ paid = dates.map { |date| create_transfer(amount: 2000, date: date, to: to, notes: reference) }
+ series = from_transfer(paid.first, day: 3)
+ series.update!(matcher_hints: { "bank_reference" => reference, "reference_only" => true })
+ series
+ end
+
+ RecurringTransaction::Pipeline.new(@family).run!
+ RecurringTransaction::HistoryBackfiller.new(@family, months: 72).run!
+ RecurringTransaction::Pipeline.new(@family).run!
+ RecurringTransaction::Matcher.new(@family).run!
+
+ linked = RecurringAllocation.where(entry_id: transfers.map(&:id)).count
+ assert_equal dates.size, linked, "cycles: #{allowance.recurring_occurrences.order(:due_on).pluck(:due_on, :status).inspect}"
+ assert_equal 0, allowance.recurring_occurrences.open_status.where("due_on < ?", Date.current).count
+ assert_equal 14, contracts.sum { |series| series.recurring_occurrences.paid.count }
+ end
+ end
+
+ private
+ def from_transfer(outflow, day:)
+ series = RecurringTransaction.create_from_transfer(Transfer.find_by!(outflow_transaction_id: outflow.entryable_id))
+ series.update!(expected_day_of_month: day)
+ series
+ end
+
+ def create_transfer(amount:, date:, to:, notes: nil)
+ outflow = @account.entries.create!(date: date, amount: amount, currency: "USD", name: "Transfer to #{to.name}", notes: notes,
+ entryable: Transaction.new(kind: "funds_movement"))
+ inflow = to.entries.create!(date: date, amount: -amount, currency: "USD", name: "Transfer from #{@account.name}",
+ entryable: Transaction.new(kind: "funds_movement"))
+ Transfer.create!(outflow_transaction: outflow.entryable, inflow_transaction: inflow.entryable, status: "confirmed")
+ outflow
+ end
+end
diff --git a/test/models/recurring_transaction_test.rb b/test/models/recurring_transaction_test.rb
index 3a83d9fae9..9a2a3ad1dc 100644
--- a/test/models/recurring_transaction_test.rb
+++ b/test/models/recurring_transaction_test.rb
@@ -11,6 +11,52 @@ class RecurringTransactionTest < ActiveSupport::TestCase
@family.recurring_transactions.destroy_all
end
+ test "bank_reference lives in matcher_hints, squished, and blank removes it" do
+ series = @family.recurring_transactions.create!(
+ name: "Water", account: @account, amount: 80, 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, matcher_hints: { "name_aliases" => [ "WATER CO" ] }
+ )
+
+ series.update!(bank_reference: " VN 4711 ")
+ assert_equal "VN 4711", series.reload.bank_reference
+ assert_equal [ "WATER CO" ], series.matcher_hints["name_aliases"], "other learned hints survive"
+
+ series.update!(bank_reference: " ")
+ assert_nil series.reload.bank_reference
+ assert_not series.matcher_hints.key?("bank_reference")
+ end
+
+ test "reference_only is stored in matcher_hints and only effective with a reference" do
+ series = @family.recurring_transactions.create!(
+ name: "Water", account: @account, amount: 80, 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
+ )
+
+ series.update!(reference_only: "1")
+ assert_not series.reference_only?, "no reference, no effect"
+
+ series.update!(bank_reference: "VN 4711")
+ assert series.reference_only?
+
+ series.update!(reference_only: "0")
+ assert_not series.reference_only?
+ assert_not series.matcher_hints.key?("reference_only")
+ end
+
+ test "a bank_reference too short to be distinctive is invalid" do
+ series = @family.recurring_transactions.new(
+ name: "Water", account: @account, amount: 80, 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, bank_reference: "ab"
+ )
+
+ assert_not series.valid?
+ assert series.errors.key?(:bank_reference)
+ end
+
+
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
@@ -2096,6 +2142,94 @@ class RecurringTransactionTest < ActiveSupport::TestCase
assert_not_includes results, on_private
end
+ test "a bank reference needs an account and an expense bill" do
+ series = @family.recurring_transactions.new(
+ name: "Water", amount: 80, 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, bank_reference: "VN 4711"
+ )
+ assert_not series.valid?
+ assert series.errors.added?(:bank_reference, :needs_account_and_expense)
+
+ series.account = @account
+ assert series.valid?
+
+ series.bill_type = "income"
+ series.amount = -80
+ assert_not series.valid?
+ end
+
+ test "reference-only reads false where a reference cannot match" do
+ series = @family.recurring_transactions.create!(
+ name: "Water", account: @account, amount: 80, 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, bank_reference: "VN 4711", reference_only: true
+ )
+ assert series.reference_only?
+
+ series.update_columns(account_id: nil)
+
+ assert_not series.reload.reference_only?
+ end
+
+ test "covering ignores a reference-only bill's name and finds it by the reference in the note" do
+ setup_covering_family
+ declared = covering_series(name: "Netflix", amount: 50)
+ declared.update!(bank_reference: "NFX 123", reference_only: true)
+ bare = create_transaction(account: @account, amount: 50, name: "Netflix")
+ referenced = create_transaction(account: @account, amount: 50, name: "something else")
+ referenced.update!(notes: "NFX 123 monthly")
+
+ assert_nil @family.recurring_transactions.covering(bare)
+ assert_equal declared, @family.recurring_transactions.covering(referenced)
+ end
+
+ test "Identifier leaves a reference-only manual bill's variance to the matcher" do
+ setup_covering_family
+ declared = covering_series(name: "Netflix", amount: 50)
+ declared.update!(bank_reference: "NFX 123", reference_only: true, occurrence_count: 9)
+ create_transaction(account: @account, amount: 50, name: "Netflix", date: Date.current)
+
+ RecurringTransaction.identify_patterns_for!(@family)
+
+ assert_equal 9, declared.reload.occurrence_count
+ end
+
+ test "covering finds a reference-only bill by its note whatever the payment's amount" do
+ setup_covering_family
+ declared = covering_series(name: "Netflix", amount: 80)
+ declared.update!(bank_reference: "NFX 123", reference_only: true)
+ entry = create_transaction(account: @account, amount: 240, name: "something else")
+ entry.update!(notes: "NFX 123 quarterly")
+
+ assert_equal declared, @family.recurring_transactions.covering(entry)
+ end
+
+ test "covering never matches a refund of the opposite sign to a reference-only bill" do
+ setup_covering_family
+ declared = covering_series(name: "Netflix", amount: 80)
+ declared.update!(bank_reference: "NFX 123", reference_only: true)
+ refund = create_transaction(account: @account, amount: -240, name: "refund")
+ refund.update!(notes: "NFX 123 refund")
+
+ assert_nil @family.recurring_transactions.covering(refund)
+ end
+
+ test "covering finds a referenced bill by the note whatever the amount, unless another merchant is bound" do
+ setup_covering_family
+ declared = covering_series(name: "Netflix", amount: 80)
+ declared.update!(bank_reference: "NFX 123")
+ entry = create_transaction(account: @account, amount: 240, name: "something else")
+ entry.update!(notes: "NFX 123 quarterly")
+
+ assert_equal declared, @family.recurring_transactions.covering(entry)
+
+ bound = covering_series(name: "Other", amount: 80, merchant: @merchant, dedup_scope: "bound")
+ bound.update!(bank_reference: "BND 555")
+ foreign = create_transaction(account: @account, amount: 240, name: "x", merchant: @family.merchants.create!(name: "Else"))
+ foreign.update!(notes: "BND 555")
+
+ assert_nil @family.recurring_transactions.covering(foreign)
+ end
+
private
# A detected bill on the outflow side of what later turns out to be a
# monthly move between two of the family's own accounts.