The personal finance app for everyone (by everyone)
Ruby
class RecurringTransaction
# The only supported write path for allocations: it holds the locks, freezes
# the amount, and refreshes close state. A direct RecurringAllocation.create!
# bypasses all three.
#
# Every write takes the occurrence row lock. Writes touching an entry also
# take an advisory lock on the ENTRY, because two allocations of one
# transaction against two different occurrences take different row locks,
# never meet, and would both read the same stale capacity.
#
# Closing has two modes, and conflating them marks half-paid rent as settled:
#
# * Actual-replaces-estimate: a SINGLE payment within the series' tolerance
# of the expected amount is the bill. Close paid.
# * Accumulation: multiple payments, or one below the band, close only when
# they sum to the full expected amount.
class Allocator
class OverAllocationError < StandardError; end
# Nothing of the entry is left: other allocations already take all of it.
# Subclasses, so every caller that refuses over-allocation refuses these
# too. AlreadyAllocatedError is the case where this occurrence is the one
# holding the entry.
class EntryExhaustedError < OverAllocationError; end
class AlreadyAllocatedError < OverAllocationError; end
# The entry is one side of a split (the parent, or one of its children)
# and the other side already pays a bill. Both sides are the same money.
class SplitCounterpartAllocatedError < OverAllocationError; end
class MissingRateError < StandardError; end
# Postgres keeps single-key and two-key advisory locks in separate spaces,
# so this cannot collide with the single-key family locks the jobs take.
ENTRY_LOCK_NAMESPACE = 8311
attr_reader :occurrence
# Takes the entry's advisory lock for the rest of the caller's transaction
# (it is transaction-scoped, so the caller must have one open). Allocation
# writes take it, and so does anything that decides from an entry's
# allocations whether to make a new series for it, so the two serialize.
def self.lock_entry!(entry)
RecurringOccurrence.lease_connection.execute(
ActiveRecord::Base.sanitize_sql_array(
[ "SELECT pg_advisory_xact_lock(?::int, ?::int)", ENTRY_LOCK_NAMESPACE, entry_lock_id(entry) ]
)
)
end
# Keyed on the split root, so a split parent and its children share one
# lock: their counterpart checks then see each other's committed writes.
def self.entry_lock_id(entry)
Digest::MD5.hexdigest((entry.parent_entry_id || entry.id).to_s).to_i(16) % (2**31)
end
# Allocations that count toward an entry's capacity: everything except
# tombstones from ended series (a deleted or dismissed bill). Counting
# those would permanently consume the entry and block re-use on a new
# bill (see #3592). Defined once so the capacity checks stay in sync.
def self.active_allocations(allocations = RecurringAllocation.all)
allocations.joins(recurring_occurrence: :recurring_transaction)
.where.not(recurring_transactions: { status: "ended" })
end
# What guard_entry_capacity! would leave of each entry for another bill,
# for many entries in one query. Entries no bill uses yet are omitted.
# Pass a narrower allocations scope to count only the bills a viewer can
# see; the guard itself always counts every allocation.
#
# The query also reads the allocations of each entry's split counterparts
# (see Entry#split_counterparts): once one side of a split pays a bill, the
# other side has nothing left.
def self.remaining_by_entry(entries, allocations: RecurringAllocation.all)
by_id = entries.index_by(&:id)
scope = active_allocations(allocations).joins(:entry)
rows = scope.where(entry_id: by_id.keys + entries.filter_map(&:parent_entry_id))
.or(scope.where(entries: { parent_entry_id: by_id.keys }))
.group(:entry_id, "entries.parent_entry_id")
.pluck(
:entry_id,
"entries.parent_entry_id",
Arel.sql("SUM(COALESCE(source_amount, allocated_amount))"),
Arel.sql("BOOL_OR(source_amount IS NULL)")
)
paying_ids = rows.map(&:first).to_set
paying_parent_ids = rows.filter_map(&:second).to_set
spent_by_counterpart = entries.select do |entry|
paying_ids.include?(entry.parent_entry_id) || paying_parent_ids.include?(entry.id)
end
remaining = rows.each_with_object({}) do |(entry_id, _parent_id, used, unmeasurable), result|
entry = by_id[entry_id]
next unless entry
result[entry_id] = unmeasurable ? 0 : [ entry.amount.abs - used, 0 ].max
end
spent_by_counterpart.each { |entry| remaining[entry.id] = 0 }
remaining
end
def initialize(occurrence)
@occurrence = occurrence
end
# Records a payment: against an entry (full or custom amount) or as an
# entry-less manual payment. Amounts are in the occurrence's currency;
# a cross-currency entry converts at its own date's rate, or requires an
# explicit amount when no rate exists.
#
# categorize: true applies the bill's category to the entry. It is opt-in
# because only the caller knows whether its user may annotate the transaction.
def allocate!(amount: nil, entry: nil, paid_on: nil, source: nil, cap_at_remaining: false, categorize: false)
occurrence.with_lock do
with_entry_lock(entry) do
allocated, source_amount, source_currency = resolve_amounts(amount, entry)
guard_entry_capacity!(entry, source_amount) if entry
freeze_expected_amount!
# Opt-in, because exceeding the remainder is load-bearing elsewhere:
# a single settlement above the expected amount is exactly how a
# price rise gets recorded and learned from. A caller that promises
# capping (the AI payment tool) enforces it HERE, under the
# occurrence lock, because its own pre-lock check is advisory only:
# two concurrent payments can both read the same stale remainder.
if cap_at_remaining && allocated > occurrence.remaining_amount
raise OverAllocationError, I18n.t("recurring_transactions.allocator.exceeds_remaining",
amount: Money.new(allocated, occurrence.currency).format,
remaining: Money.new(occurrence.remaining_amount, occurrence.currency).format)
end
allocation = occurrence.allocations.create!(
entry: entry,
allocated_amount: allocated,
currency: occurrence.currency,
source_amount: source_amount,
source_currency: source_currency,
state: "confirmed",
source: source || (entry ? "user_confirmed" : "user_created"),
paid_on: paid_on
)
learn_from_manual_attach!(allocation) if entry
allocation = promote_settlement!(allocation) if entry && amount.blank?
apply_bill_category!(entry) if categorize
refresh_close_state!
allocation
end
end
end
def unallocate!(allocation)
occurrence.with_lock do
with_entry_lock(allocation.entry) do
allocation.destroy!
refresh_close_state!
end
end
end
# The Matcher's write path: confirmed at the exact tier, suggested at the
# high tier. Suggestions never move close state.
def allocate_matched!(entry:, state:, confidence:, signals:)
occurrence.with_lock do
with_entry_lock(entry) do
# 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)
freeze_expected_amount! if state == "confirmed"
allocation = occurrence.allocations.create!(
entry: entry,
allocated_amount: allocated,
currency: occurrence.currency,
source_amount: source_amount,
source_currency: source_currency,
state: state,
source: "auto_matched",
match_confidence: confidence,
match_signals: signals,
paid_on: entry.date
)
if state == "confirmed"
apply_bill_category!(entry) if matcher_may_categorize?(entry)
refresh_close_state!
end
allocation
end
end
end
# Accepting a suggestion makes it a real payment.
#
# categorize: true for a caller whose user may annotate the transaction; a
# read-only account share links a payment without editing it.
def confirm_suggestion!(allocation, categorize: false)
occurrence.with_lock do
with_entry_lock(allocation.entry) do
freeze_expected_amount!
# Only the move from suggested to confirmed makes a payment: a replayed
# confirmation of a confirmed one must not categorize it later.
first_confirmation = allocation.reload.allocation_suggested?
allocation.update!(state: "confirmed", source: "user_confirmed")
apply_bill_category!(allocation.entry) if categorize && first_confirmation
refresh_close_state!
end
end
end
# The Matcher re-attached a confirmed payment to the transaction that
# replaced its original (a provider reposting it): the replacement is the
# payment now, so it takes the bill's category the original would have.
def categorize_reattached!(allocation)
occurrence.with_lock do
# The caller's copy may predate a confirmation, so the state is read
# again under the lock.
allocation.reload
next unless allocation.allocation_confirmed? && allocation.entry
with_entry_lock(allocation.entry) do
apply_bill_category!(allocation.entry) if matcher_may_categorize?(allocation.entry)
end
end
end
# Records the (series, entry) pair so the matcher never proposes it again.
def reject_suggestion!(allocation)
occurrence.with_lock do
with_entry_lock(allocation.entry) do
if allocation.entry
RecurringMatchRejection.find_or_create_by!(
recurring_transaction: occurrence.recurring_transaction,
entry: allocation.entry
)
end
allocation.destroy!
end
end
end
# Settles the remainder with no transaction, as a user decision, so it
# never auto-reopens. A backdated settlement carries its real payment date
# into the history instead of defaulting to today.
def mark_paid!(paid_on: nil)
occurrence.with_lock do
freeze_expected_amount!
remaining = occurrence.remaining_amount
if remaining.positive?
occurrence.allocations.create!(
allocated_amount: remaining,
currency: occurrence.currency,
state: "confirmed",
source: "user_created",
paid_on: paid_on
)
end
occurrence.reload
occurrence.close!("paid", source: "user") if occurrence.scheduled?
end
end
# Re-derives the stored close state from the confirmed allocations:
# closes an open occurrence that now qualifies, reopens an auto-closed one
# that no longer does. User-closed occurrences never auto-reopen.
def refresh_close_state!
occurrence.reload
if occurrence.scheduled?
occurrence.close!("paid", source: "auto") if close_worthy?
elsif occurrence.paid? && occurrence.closed_source == "auto" && !close_worthy?
occurrence.reopen!
end
end
private
# Serializes every write touching this entry, whichever occurrence it
# targets. Always taken inside the occurrence row lock, so the ordering is
# occurrence then entry and no pair can deadlock.
def with_entry_lock(entry)
return yield if entry.nil?
self.class.lock_entry!(entry)
yield
end
# A confirmed payment pins the obligation it was made against. Open rows
# otherwise inherit their amount from the series, which is correct until
# money has moved: after that, re-resolving would re-target a payment the
# user already made. Suggestions pin nothing.
def freeze_expected_amount!
return if occurrence.expected_amount.present?
occurrence.update!(expected_amount: occurrence.resolved_expected_amount)
end
# A bill's category says what its payments are, so a payment confirmed
# against it picks that category up. Only a blank, unlocked category is
# filled: anything the user, a rule or a provider already decided stays,
# and releasing the payment later leaves the category in place. Not
# locked afterwards, so the user can still change it and a rule can still
# override it.
#
# The transaction row is locked and re-read first: the Matcher loaded it
# before getting here, so a category the user committed since would still
# look blank on the loaded copy and be overwritten.
def apply_bill_category!(entry)
category_id = occurrence.recurring_transaction.category_id
return if category_id.blank? || entry.nil?
transaction = entry.entryable
return unless transaction.is_a?(Transaction)
transaction.with_lock do
next unless transaction.category_id.blank? && transaction.category_editable?
next unless Category.exists?(id: category_id)
transaction.enrich_attribute(:category_id, category_id, source: "recurring_bill")
end
rescue ActiveRecord::InvalidForeignKey
# The category was deleted between the check and the write. The payment
# is still a payment; it just stays uncategorized.
nil
end
# Matching runs with no signed-in user, so the user-facing access check
# cannot be made. A bill tied to an account only ever matches that
# account's transactions, and whoever may edit the bill may annotate them.
# A bill that is not tied to an account matches the whole family, so the
# matcher categorizes nothing for it; it is categorized when a person
# confirms the payment, with that person's own access.
def matcher_may_categorize?(_entry)
occurrence.recurring_transaction.account_id.present?
end
def close_worthy?
expected = occurrence.resolved_expected_amount
return false unless expected.positive?
confirmed = occurrence.allocations.confirmed.to_a
return false if confirmed.empty?
# 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
tolerance = expected * (occurrence.recurring_transaction.effective_amount_tolerance_pct / BigDecimal("100"))
return true if (confirmed.first.allocated_amount - expected).abs <= tolerance
end
total >= expected - RecurringOccurrence::CLOSE_EPSILON
end
def resolve_amounts(amount, entry, reference: false)
if entry.nil?
raise ArgumentError, "an amount is required for a payment without a transaction" if amount.blank?
return [ BigDecimal(amount.to_s), nil, nil ]
end
entry_total = entry.amount.abs
if entry.currency == occurrence.currency
allocated = if amount.present?
BigDecimal(amount.to_s)
else
# Default: as much of the entry as this occurrence still needs --
# or, when the occurrence is already covered, the entry's whole
# unspoken-for amount (an explicit overpay attach). Either way it
# is bounded by what the entry has left: an exhausted entry
# allocates nothing, never the occurrence's outstanding balance.
capacity = entry_capacity(entry, entry_total)
remaining = occurrence.remaining_amount
if settles_bill?(entry, entry_total, reference: reference)
capacity
else
remaining.positive? ? [ capacity, remaining ].min : capacity
end
end
[ allocated, allocated, entry.currency ]
else
rate = ExchangeRate.find_or_fetch_rate(from: entry.currency, to: occurrence.currency, date: entry.date)&.rate
if amount.present?
allocated = BigDecimal(amount.to_s)
source = rate ? (allocated / BigDecimal(rate.to_s)).round(4) : nil
[ allocated, source, entry.currency ]
elsif rate
# Bounded the same way the same-currency default is: by what is
# left of the entry and what the occurrence still owes. Defaulting
# to the entry's full total meant a partly allocated foreign
# transaction could never be attached without an explicit amount,
# because the guard rejected the untaken remainder's own default.
source = entry_capacity(entry, entry_total)
converted = (source * BigDecimal(rate.to_s)).round(4)
remaining = occurrence.remaining_amount
if remaining.positive? && remaining < converted
[ remaining, (remaining / BigDecimal(rate.to_s)).round(4), entry.currency ]
else
[ converted, source, entry.currency ]
end
else
raise MissingRateError, I18n.t("recurring_transactions.allocator.missing_rate",
from: entry.currency, to: occurrence.currency)
end
end
end
# Actual-replaces-estimate: an entry that is the bill itself is recorded at
# 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. 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?
within_settlement_band?(entry_total)
end
def within_settlement_band?(entry_total)
expected = occurrence.resolved_expected_amount
return false unless expected.positive?
tolerance = expected * (occurrence.recurring_transaction.effective_amount_tolerance_pct / BigDecimal("100"))
(entry_total - expected).abs <= tolerance
end
# A manual link can teach the band that covers it (learn_from_manual_attach!),
# but only after its own allocation was capped. When the band it just taught
# now covers this payment, and it is the only settlement of the bill and the
# only use of the entry, record the whole entry so the history shows what
# was actually paid. Explicit amounts are never changed.
def promote_settlement!(allocation)
entry = allocation.entry
return allocation unless entry.currency == occurrence.currency
return allocation unless occurrence.allocations.confirmed.count == 1
return allocation unless active_allocations_for(entry).count == 1
entry_total = entry.amount.abs
return allocation if allocation.allocated_amount == entry_total
return allocation unless within_settlement_band?(entry_total)
allocation.update!(allocated_amount: entry_total, source_amount: entry_total)
allocation
end
def active_allocations_for(entry)
self.class.active_allocations.where(entry: entry)
end
# True once any allocation on this entry (excluding those from ended
# series) lacks a source amount, which makes every capacity sum over it
# meaningless.
def unmeasurable_entry?(entry)
active_allocations_for(entry).where(source_amount: nil).exists?
end
# How much of the entry is not yet spoken for, in the entry's currency.
def entry_capacity(entry, entry_total)
already = active_allocations_for(entry)
.sum("COALESCE(recurring_allocations.source_amount, recurring_allocations.allocated_amount)")
[ entry_total - already, 0 ].max
end
# Two transparent things a manual attach can teach the matcher, both
# stored in the series' user-visible matcher_hints:
#
# * An alias: a name-keyed series attached to an entry it would not
# have recognized -- next time the matcher will.
# * A wider tolerance: when this SINGLE entry essentially is the bill
# and its amount sits outside the band, the band was too tight.
# Partial payments teach nothing -- a $537.50 installment against
# $2,150 rent is not evidence that rent varies. Being the only
# allocation does not make a payment the bill, so the test is
# whether it actually SETTLES the occurrence.
def learn_from_manual_attach!(allocation)
series = occurrence.recurring_transaction
entry = allocation.entry
hints = series.matcher_hints.deep_dup
if series.merchant_id.blank? && series.name.present?
known = ([ series.matcher_name ] + Array(hints["name_aliases"]))
.map { |name| Matcher.normalize_name(name) }
unless known.include?(Matcher.normalize_name(entry.name))
hints["name_aliases"] = (Array(hints["name_aliases"]) + [ entry.name ]).uniq
end
end
expected = occurrence.resolved_expected_amount
if expected.positive? && occurrence.allocations.confirmed.count == 1 && close_worthy?
deviation_pct = (entry.amount.abs - expected).abs / expected * 100
current = BigDecimal(hints["learned_tolerance_pct"].to_s, exception: false)
current = BigDecimal("0") unless current&.finite?
if deviation_pct > series.amount_tolerance_pct &&
deviation_pct > current &&
deviation_pct <= Matcher::MAX_LEARNED_TOLERANCE_PCT
# Round up: a deviation of 7.55% stored as 7.5% would leave the
# very payment that taught it outside its own band.
hints["learned_tolerance_pct"] = ((deviation_pct * 10).ceil / BigDecimal(10)).to_f
end
end
series.update!(matcher_hints: hints) if hints != series.matcher_hints
end
# One transaction can pay several occurrences, but never more than
# itself. Compared in the ENTRY's currency via source_amount.
#
# An allocation with no exchange rate for its date has no source amount,
# so it cannot be expressed in the entry's currency, and neither it nor
# anything beside it can be measured against the transaction total.
# Exempting those outright meant a single 100 EUR transaction could be
# allocated 150 USD twice over, and indeed without limit: capacity summed
# COALESCE(source_amount, allocated_amount), mixing currencies into a
# number that meant nothing.
#
# The first such allocation is a judgement the user made about a
# transaction they can see. A second one is a transaction silently paying
# an unbounded number of bills, so an unmeasurable entry takes no more
# than one. Allocations from ended series are excluded throughout so a
# deleted bill never blocks re-use of the same entry on a replacement.
def guard_entry_capacity!(entry, source_amount)
# A split parent and its children are the same money, so whichever
# side pays a bill first (a suggestion included) takes the other side
# out. Otherwise the parent could pay one bill and a child another,
# counting more than the bank charged.
if active_allocations_for(entry.split_counterparts).exists?
raise SplitCounterpartAllocatedError, I18n.t("recurring_transactions.allocator.split_counterpart_allocated")
end
if source_amount.nil? || unmeasurable_entry?(entry)
return if active_allocations_for(entry).none?
raise OverAllocationError, I18n.t("recurring_transactions.allocator.unmeasurable",
currency: entry.currency, date: entry.date)
end
capacity = entry_capacity(entry, entry.amount.abs)
# The default amount is bounded by what the entry has left, so an
# exhausted entry defaults to zero. Zero passes the comparison below
# and used to surface only as the allocation's own "greater than 0"
# validation, which the user read as an unexplained failure.
unless capacity.positive?
# Used up by THIS occurrence means a repeated link (a double submit,
# a stale tab). With capacity left the unique index reports that as
# already allocated, and "other payments due" would be untrue here.
if occurrence.allocations.exists?(entry: entry)
raise AlreadyAllocatedError, I18n.t("recurring_transactions.allocator.already_allocated")
end
raise EntryExhaustedError, I18n.t("recurring_transactions.allocator.entry_exhausted")
end
if source_amount > capacity + RecurringOccurrence::CLOSE_EPSILON
raise OverAllocationError, I18n.t("recurring_transactions.allocator.over_allocated",
amount: source_amount, capacity: capacity,
currency: entry.currency)
end
end
end
end