The personal finance app for everyone (by everyone)
Ruby
# Links an existing transaction into a confirmed transfer, either with an
# existing opposite transaction (one of Transaction#transfer_match_candidates)
# or with a new counterpart entry created in a target account.
#
# This is the same operation as TransferMatchesController#create and
# Rule::ActionExecutor::SetAsTransferOrPayment, which predate this class.
# Kinds and the Investment Contributions category come from Transfer#confirm!,
# as there. Permission checks are the caller's job: this class enforces only
# the data rules.
class Transfer::Matcher
class Error < StandardError
attr_reader :code
def initialize(code, message)
@code = code
super(message)
end
end
# The manual match dialog's window. Transfer validation allows confirmed
# transfers up to 30 days apart.
DATE_WINDOW = 30
attr_reader :transaction
def initialize(transaction)
@transaction = transaction
end
# Only pairs match_with! accepts: the family query already skips excluded
# entries (including split parents), so split children are dropped here.
def candidates(date_window: DATE_WINDOW)
return [] if entry.excluded? || entry.split_child?
filter = entry.amount.negative? ? { inflow_transaction_id: transaction.id } : { outflow_transaction_id: transaction.id }
rows = family.transfer_match_candidates(
date_window: date_window,
exchange_rate_tolerance: Family::AutoTransferMatchable.manual_match_exchange_rate_tolerance,
**filter
)
split_child_ids = Entry.where(entryable_type: "Transaction", entryable_id: rows.map { |row| counterpart_id(row) })
.where.not(parent_entry_id: nil)
.pluck(:entryable_id)
.to_set
rows.reject { |row| split_child_ids.include?(counterpart_id(row)) }
end
# The other transaction in a candidate row.
def counterpart_id(row)
row.inflow_transaction_id == transaction.id ? row.outflow_transaction_id : row.inflow_transaction_id
end
# With dry_run: true, runs every check and returns the unsaved transfer.
def match_with!(counterpart, dry_run: false)
link!(transaction, counterpart, dry_run:) do
ensure_matchable!(transaction)
ensure_matchable!(counterpart)
unless candidates.any? { |row| counterpart_id(row) == counterpart.id }
raise Error.new(:not_a_candidate, "The two transactions cannot form a transfer: they need opposite, matching amounts in different accounts of the same family, at most #{DATE_WINDOW} days apart.")
end
entry.amount.negative? ? [ transaction, counterpart ] : [ counterpart, transaction ]
end
end
def match_to_account!(account, dry_run: false)
link!(transaction, dry_run:) do
ensure_matchable!(transaction)
raise Error.new(:same_account, "The target account must differ from the transaction's account.") if account.id == entry.account_id
raise Error.new(:account_not_found, "The target account must belong to the same family.") unless account.family_id == entry.account.family_id
# Built in memory; saved together with the transfer by link!.
counterpart = Transaction.new(
entry: account.entries.build(
amount: entry.amount * -1,
currency: entry.currency,
date: entry.date,
name: "Transfer to #{entry.amount.negative? ? entry.account.name : account.name}",
user_modified: true
)
)
entry.amount.negative? ? [ transaction, counterpart ] : [ counterpart, transaction ]
end
end
private
def entry
transaction.entry
end
def family
entry.account.family
end
def ensure_matchable!(txn)
txn_entry = txn.entry
raise Error.new(:split_transaction, "Split transactions cannot be matched as transfers.") if txn_entry.split_parent? || txn_entry.split_child?
raise Error.new(:excluded_transaction, "Excluded transactions cannot be matched as transfers.") if txn_entry.excluded?
raise Error.new(:already_linked, "The transaction is already part of a transfer.") if txn.transfer.present?
end
# Two concurrent matches of one transaction (with different counterparts)
# could otherwise both pass the checks; the unique index only covers the
# pair. Lock the persisted transactions and their entries in a fixed
# order, then reload them so the checks see what is committed now
# (another transfer, an exclusion, a split, a changed amount or date).
def lock_and_reload!(txns)
ids = txns.map(&:id).sort
Transaction.where(id: ids).order(:id).lock.pluck(:id)
Entry.where(entryable_type: "Transaction", entryable_id: ids).order(:id).lock.pluck(:id)
txns.each(&:reload)
end
# The block runs the checks and returns [inflow, outflow]. For a real
# match it runs under the locks, uncached so no read is answered from a
# query cache filled before the lock.
def link!(*txns, dry_run:)
if dry_run
transfer = build_transfer(*yield)
raise Error.new(:invalid_transfer, transfer.errors.full_messages.to_sentence) unless transfer.valid?
return transfer
end
transfer = nil
Transfer.uncached do
Transfer.transaction do
lock_and_reload!(txns)
inflow, outflow = yield
transfer = build_transfer(inflow, outflow)
transfer.save!
transfer.confirm!
end
end
transfer.sync_account_later
transfer
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique => e
raise Error.new(:invalid_transfer, e.message)
end
def build_transfer(inflow, outflow)
Transfer.new(
inflow_transaction: inflow,
outflow_transaction: outflow,
status: "confirmed",
amount: outflow.entry.amount.abs
)
end
end